Python Tutorial
#!/usr/bin/python import sys; print sys.argv;Output:
$ python test_command_line_args.py 1 2 3 ['test_command_line_args.py', '1', '2', '3']
$ python test_command_line_args.py ['test_command_line_args.py']Here sys.argv[0] is the python scripts file name.
#!/usr/bin/python import sys; print("Command Line Arguments Count: %d" % len(sys.argv)); for i, arg in enumerate(sys.argv): print("Argument %d: %s" % (i, str(arg)));Output:
$ python test_command_line_args.py 1 2 3 "commandline args" Command Line Arguments Count: 5 Argument 0: test_command_line_args.py Argument 1: 1 Argument 2: 2 Argument 3: 3 Argument 4: commandline args
getopt.getopt(command_line_arguments, options[, long_options])Example
getopt.getopt(argv,"s:d:",["file1=","file2="])here argv is th command line arguments, s and d are options but s requires aregument value mandatory otherwise throws getopt.GetoptError exception.
#!/usr/bin/python import sys, getopt def parse_command_line_options(argv): source_file = ""; dest_file = ""; try: # parsing command line arguments as option and argument pairs. # here s and d are options options, args = getopt.getopt(argv,"s:d:",["file1=","file2="]) except getopt.GetoptError: print("test_command_line_args.py -sDiffernt Scenario's Output:
# if no options are given in command line arguments $ python test_command_line_args.py 1 2 3 "commandline args" Source file: Destination file: # if both options are given with arguments in command line arguments [jaganathan@dhcp35-211 python]$ python test_command_line_args.py -s "file_input.txt" -d "file_output.txt" Source file: file_input.txt Destination file: file_output.txt # if both options are given but only s option has argument value in command line arguments [jaganathan@dhcp35-211 python]$ python test_command_line_args.py -s "file_input.txt" Source file: file_input.txt Destination file: # if only d option is given with argument value in command line arguments [jaganathan@dhcp35-211 python]$ python test_command_line_args.py -d "file_output.txt" Source file: Destination file: file_output.txt # if unknown option is given, raises exception and prints message [jaganathan@dhcp35-211 python]$ python test_command_line_args.py -h "file_output.txt" test_command_line_args.py -s
Python Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page