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.
To experiment with command-line arguments, save this script and run it from the command line:
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
.