Is it possible to pass arguments into a Python script?

This worked for me:

import sys
firstarg=sys.argv[1]
secondarg=sys.argv[2]
thirdarg=sys.argv[3]

You can use the argv from sys

from sys import argv
arg1, arg2, arg3, ... = argv

You can actually put an abitrary number of arguments in the command line. argv will be a list with the arguments. Thus it can also be called as arg1 = sys.argv[0] arg2 = sys.argv[1] . . .

Keep also in mind that sys.argv[0] is simply the name of your python program. Additionally, the "eval" and "exec" functions are nice when you use command line input. Usually, everything in the command line is interpreted as a string. So, if you want to give a formula in the command line you use eval().

>>> x = 1
>>> print eval('x+1')
2

Tags:

Python