If you are writing a Python program to accept command line arguments, the
arguments passed on the command line are accessed as sys.argv. Here's a
simple example, save it as command.py:
#!/usr/bin/env python if __name__ == '__main__': import sys print "Executable: %s"%sys.argv[0] for arg in sys.argv[1:]: print "Arg: %s"%argThe if __name__ == '__main__': line ensures the code beneath it only gets run if the file is executed, not if it is imported. Make this file executable:
$ chmod 755 command.pyHere are some examples of this being run:
$ python command.py Executable: command.py $ python command.py arg1 Executable: command.py Arg: arg1 $ python command.py arg1 arg2 Executable: command.py Arg: arg1 Arg: arg2Notice that sys.argv[0] always contains the name of the script which was executed, regardless of how Python was invoked. sys.argv[1] and onward are the command line arguments. You can also invoke the program using Python's -m switch to run it as a module import:
$ python -m command Executable: /home/james/Desktop/command.py $ python -m command arg1 Executable: /home/james/Desktop/command.py Arg: arg1 $ python -m command arg1 arg2 Executable: /home/james/Desktop/command.py Arg: arg1 Arg: arg2Once again, Python works out that python -m command are all part of the invoking command so sys.argv[0] only contains the path of the Python script. Let's try executing it directly:
$ ./command.py Executable: ./command.py $ ./command.py arg1 Executable: ./command.py Arg: arg1 $ ./command.py arg1 arg2 Executable: ./command.py Arg: arg1 Arg: arg2As you can see, sys.argv[0] still contains the Python script and sys.argv[1] and onwards represent each argument.
Comments
Post a Comment
https://gengwg.blogspot.com/