Lesson 22:

Launching Python in Other Programs

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.

Temporarily edit the PATH in OSX

Show PATH in Terminal

$ echo $PATH

Temporarily add to $PATH for that terminal session

$ PATH=/usr/bin:/bin:/usr/sbin:/newpathtofolder/

Permanently edit the PATH in OSX

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)


Hello world
['/usr/local/lib/python3.5/site-packages/ipykernel/__main__.py', '-f', '/Users/vivek.menon/Library/Jupyter/runtime/kernel-3f335b24-2ae5-4241-b273-c5438dbe2b62.json']

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'

Recap

  • The shebang line tells your computer that you want to run the script using Python 3.
  • On Windows, you can bring up the Run dialog by pressing <Win>+R. OSX/Unix uses Terminal.
  • A batch file can save you a lot of typing by running multiple commands.
  • You can add a folder to the $PATH environment variable to skip absolute paths.
  • Command line arguments can be read via the sys.argv list.