The first line of any Pthon Script should be the Shebang Line.
OSX:
#! /usr/bin/env python3
Linux:
#! usr/bin/python3
Windows:
python3
This lets you run scrips in Terminal/CMD Prompt.
python3 /path/to/script.py
Batch files, or shell scripts, can run multiple seperate programs/scripts.
OSX/Linux:
.sh
Windows:
.bat
A shell script includes references to multiple programs:
In [38]:
#! usr/bin/env bash
# This is a shell script
#python3 runthisscript.py
#echo 'I'm running a python script'
You can then use CMD/Terminal to run this script
$sh /path/to/shellscript.sh
You can skip adding the absolute path to scripts by adding folders to the PATH environment variable.
This lets the operating system check these folders before looking anywhere else. Editing the PATH gives the entire OS access to those folders from any location.
Show PATH in Terminal
$ echo $PATH
Temporarily add to $PATH for that terminal session
$ PATH=/usr/bin:/bin:/usr/sbin:/newpathtofolder/
Move to home folder
$ cd
Edit the .bash_profile (use whatever editor you want instead of 'nano')
$nano .bash_profile #
Add the new value to the PATH and include exiting folders (with :PATH)
$ export PATH="/usr/local/mysql/bin:$PATH"
Should now show the new PATH with the added folder.
$ echo $PATH
Scripts can also take command line arguments:
sh script.sh arg1 arg2
These are called system arguments, and can be accessed in a Python program via the sys.argv
command.
In [32]:
import sys
print('Hello world')
print(sys.argv)
This is useful for allowing your program to take additional parameters when incorporated into batch files.
Typically, you will need to add a %*
to forward those arguments to the Python script:
In [ ]:
#! usr/bin/env bash
# This is a shell script
#python3 runthisscript.py %*
#echo 'I'm running a python script with system arguments'
<Win>+R
. OSX/Unix uses Terminal.sys.argv
list.