Command Line Arguments in Python

Command-line arguments are a common way to parameterize execution of programs. For example, python script.py uses script.py as an argument to the python program.

import sys

def main():
    # sys.argv provides access to raw command-line arguments. 
    # Note that the first value in this list is the path to the program, 
    # and sys.argv[1:] holds the arguments to the program.
    args_with_prog = sys.argv
    args_without_prog = sys.argv[1:]

    # You can get individual args with normal indexing.
    arg = sys.argv[3]

    print(args_with_prog)
    print(args_without_prog)
    print(arg)

if __name__ == "__main__":
    main()

To experiment with command-line arguments, save this script and run it from the command line:

$ python command_line_arguments.py a b c d
['command_line_arguments.py', 'a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
c

In Python, we use the sys.argv list to access command-line arguments. The first element (sys.argv[0]) is always the name of the script itself, and the remaining elements are the arguments passed to the script.

Unlike compiled languages, Python scripts are typically run directly without a separate compilation step. The if __name__ == "__main__": idiom is used to ensure that the main() function is only called when the script is run directly, not when it’s imported as a module.

Next, we’ll look at more advanced command-line processing with argument parsing libraries like argparse.