96. Passing arguments to Python from the command line (or other programs)

Many Python programs have all the variables defined within the Python code (or the Python code reads input files). It my be useful at times, however, to be able to pass one or more arguments to Python when calling the program from the command line or another programme. This is simple in Python. Below is an example (saved as ‘mycode.py’) that takes two arguments and multiplies them together:

import sys

x,y = int(sys.argv[1]), int(sys.argv[2])

print (x * y)

Now we can call that from the command line, passing our variables:

python mycode.py 3 4


This type of code may allow us to write generic Python code, and call it as part of an automated sequence from another piece of code which passes the required variables to Python.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s