Python sys module (argv attribute in sys module) is used to access any command-line arguments.
sys.argv is the list of command-line arguments.
len(sys.argv) is the number of command-line arguments.
Accessing Command Line Arguments
Following program is used to get command line arguments count and prints the command line arguments value with corresponding list index.
#!/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)));
here argv is th command line arguments, s and d are options but s requires aregument value mandatory otherwise throws getopt.GetoptError exception.
file1 and file2 are long options used to get option arguments.
Exception getopt.GetoptError
This exception is raised when an unrecognized option is found in the argument list or when an option requiring an argument but not given (none value).
#!/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 -s -d ");
sys.exit(1);
for option, arg in options:
if option in ("-s", "--file1"):
source_file = arg
elif option in ("-d", "--file2"):
dest_file = arg
print("Source file: %s" % source_file);
print("Destination file: %s" % dest_file);
if __name__ == "__main__":
parse_command_line_options(sys.argv[1:]);
Differnt 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 -d
# if s option with no argument value, then raises exception and prints message.
$ python test_command_line_args.py -s
test_command_line_args.py -s -d