Launching Python Program from Command Line

Shebang Line

The shebang line #! python3 tells your computer that you want to run the script using Python 3.

In [1]:
#! python3
print('Hello World')
Hello World
OS Shebang Line
Windows #! python3
OS X #! /usr/bin/env python3
Linux #! /usr/bin/python3

Save you file as hello.py in c:\users\[name]\MyPythonScripts

To run your script outside of IDLE, type the following at the command prompt

v3.4 py.exe c:\users\[name]\MyPythonScripts\hello.py

v3.6 python.exe c:\users\[name]\MyPythonScripts\hello.py

Remember to use tab completion. This will save a lot of typing

Batch Files/ Shell Scripts

A batch file can save you a lot of typing by running multiple commands. The batch file you'll make will look like this:

@python z:\it\python\MyPythonScripts\hello.py %*
@pause

@ hides the display of the line %* forward any command line arguments to the python program pause calls the 'pause.exe' program in Windows

If the script have nothing to display on screen, you can either skip the line @pause or use pythonw/ pyw instead of python/py

Use Win+R to open the Windows Run Dialog, type

python c:\users\[name]\MyPythonScripts\hello.bat

or with no file extension 'bat'

python c:\users\[name]\MyPythonScripts\hello

The PATH environment variable

You can shorten the command to type at the Windows Run Dialog or Command Line by adding the directory containing your python scripts in your PATH environment variable.

Open the Windows Run Dialog: Win+R Run the script 'hello.bat': hello

Command Line Argument

Command line arguments can be accessed via variable sys.argv Modify the hello.py as follows and save the file

In [2]:
#! python3
print('Hello World')

import sys
print(sys.argv)
Hello World
['C:\\Users\\KL\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py', '-f', 'C:\\Users\\KL\\AppData\\Roaming\\jupyter\\runtime\\kernel-84e96257-4f18-4d7a-a7f9-7865d4f3e630.json']

Run hello arg1 arg2 at Windows Run Dialog and you'll get the following output

Hello World
['[path]\hello.py', 'arg1', 'arg2']
Press any key to continue . . .