input()
and raw_input()
, command-line arguments provide an alternative approach to passing input during the execution of a program. This method is especially useful for executing scripts with different configurations without modifying the code.In this guide, we will explore what command-line arguments are, how to use them, and the two popular modules in Python that facilitate this process: sys and getopt.sys
Module for Command-Line Argumentsargv
, which stores the arguments passed to the script, including the script name itself.sys.argv
sys
module.cmd.py
and run the following command from the terminal:cmd.py
) is the name of the script itself, while FACEPrep
and Python
are the user-provided command-line arguments.argv
Listsys
module, all command-line arguments are stored in the argv
list. The first item, argv[0]
, is always the script’s name, followed by the user inputs. You can also determine how many arguments have been passed using the len()
function:getopt
Modulesys
module is simple to use, the getopt module provides more advanced features for parsing command-line arguments. It supports both short options (e.g., -h
) and long options (e.g., --help
), making it ideal for handling complex input scenarios.getopt
Modulegetopt
module has two primary functions for parsing command-line arguments:getopt
for Command-Line Options--caps
option is used to convert the input argument to uppercase.getopt
Exception: GetoptError
GetoptError
gnu_getopt
Functiongnu_getopt()
function is similar to getopt()
, but it supports GNU-style argument parsing, where options and arguments can be intermixed. This is useful when options are not passed in a specific order.gnu_getopt()
:sys
and getopt
ModulesFeature | sys Module | getopt Module |
---|---|---|
Use Case | Basic argument handling | Advanced argument parsing with options |
Complexity | Simple, no option parsing | Supports short and long options, more control |
Arguments Format | Arguments as a list of strings | Options and arguments parsed with flags |
sys
module or advanced parsing with the getopt
module, Python provides excellent tools for dealing with user inputs in a flexible way.By mastering command-line arguments, you can write more versatile Python scripts that can be easily configured and run in different environments. Click Here to Know more!