Python Network Programming
上QQ阅读APP看书,第一时间看更新

Passing arguments from the command line

Sometimes it is necessary to pass arguments to the script from the command line. This is generally needed when we need to perform some quick actions in our script, rather than the script asking us for the inputs.

Consider the following lines of code where we pass two numbers as arguments to scripts, and print the sum of them:

import sys
print ("Total output is ")
print (int(sys.argv[1])+int(sys.argv[2]))

When we run this script, say it's saved as checkargs.py, and execute it as follows:

python checkargs.py 5 6

The output returned is as follows:

Total output is
11

The key here is the import of the sys module, which is a predefined module in Python to handle any system-related tasks of Python. The values that we pass as arguments are stored in sys.argv[1] onwards, since sys.argv[0] is the name of actual script being run. In this case, sys.argv[0] will be checkargs.py, sys.argv[1] will be 5, and sys.argv[2] will be 6.

The PowerShell code for the preceding task is as follows:

#PowerShell sample code
$myvalue=$args[0]
write-host ("Argument passed to PowerShell is "+$myvalue)
The arguments passed in a Python script are in string format, so we need to explicitly convert them to the right type for the expected output. In the preceding script, if we had not converted it to the integer type by using the int() function, then the output would have been 56 instead of int(5) + int(6) = 11.