Running Python Command Line and Getting Arguments



When you are writing a python program and want to run the Python script as a command from the terminal, you may want to get the arguments to the python program from command line. For example, you might want to execute the Python script and use its arguments.

Python myPythonWithArguments.py input1 input2

Python’s sys module’s method argv offers a neat solution to get the arguments as a list and use it in the program as variables.

>>> import sys
>>> print sys.argv
[‘myPythonWithArguments.py’, ‘input1’, ‘input2’]

A key thing to note is that all the input arguments in the sys.argv list are strings. So, if one of the arguments is a number, you have to convert to the number.

Trackbacks

  1. […] Excerpt from: Running Python Command Line and Getting Arguments […]