Linux Format

Processing command line arguments

-

When you execute a Linux command or a script you usually provide some text after the name of the program, which are called command line arguments, can be accessed in every programmin­g language and Python 3 is no exception. Traditiona­lly, command line arguments on a UNIX system are stored using an array or a similar data structure—the first element of the array, which has an index number of 0, is usually the name of the program itself!

You can process command line arguments in Python 3 as follows: #!/usr/bin/env python3 import os import sys print('All arguments:’, str(sys.argv)) for i in sys.argv[1:]:

print(i) If you name the previous Python code as aStrangeSc­riptName.py, make it executable and run it, you will get the next output: $ ./aStrangeSc­riptName.py 1 2 -w All arguments: [’./aStrangeSc­riptName.py’, ‘1’,

‘2’, ‘-w'] 1 2 -w

As you can see, the first print() command displays all of the arguments, whereas the for loop goes on to process all the arguments one by one while ignoring the first one, which is the name of the script.

However, as you saw in myWC.py, in the main tutorial, using a module such as argparse can make your life a lot easier!

Newspapers in English

Newspapers from Australia