We’ll be covering the following topics in this tutorial:
What is command line arguments in Python?
You can find Command line arguments in almost every modern programming languages, including C, C++, PHP, Java and others. Python Command line arguments are given after the script name while executing it on the terminal. We also have command-line options to set some specific options for the script.
Syntax
The syntax to write command-line arguments in python is (name of the script, the number of arguments, arguments).
python main.py arg1 arg2
Command-line arguments always stored in the form of strings. So as with information returned from the input function you might have to convert this string info to numerical format. Python provides built-in modules to take the user inputs which passed from the command prompt.
Import sys Module in Python
To access these arguments, first import the sys library:
Syntax:
import module_name
Example:
import sys
Python command line arguments example
//Python Code (demo.py): import sys print("This is my first script:"),sys.argv[0] print("Number of arguments:",len(sys.argv)) print("Argument List:",str(sys.argv))
The Python sys module access to arguments via sys.argv. It solves two purposes:
• sys.argv[0] is the script name.
• len(sys.argv) is the Number of arguments that you have in your command line.
• str(sys.argv) is the list of command-line arguments.
Executing Python
thakur@server:~ python demo.py argument1 argument2 argument3
Sample Output:
1 2 3 | This is my first script: demo.py ('Number of arguments:', 4) ('Argument List:', "['test.py', 'argument1', 'argument2', 'argument3']") |
What is argument passing?
The phrases parameter and argument are used synonymously, but there’s a difference. Parameters are within functions or procedures, while arguments are used in procedure calls, i.e., the values passed into the function in run-time.
Passing parameter data from the calling function (Method) into the called function (method) is called argument passing. Also, the arguments which calling function sends to called function are called actual arguments, and the parameters of the called function are called formal arguments. Using argument passing, we could share information from one scope to another from the Python programming language. We can pass arguments to the functions based on requirements.
Python Modules for Command Line Arguments
Python 3 supports several different libraries that allow dealing with command-line arguments.
• Python sys.argv module.
• Python getopt module
• Furthermore, two other standard methods exist.
The argparse module, which derived from the optparse module available up to Python 2.7. The other is docopt module, which is available on GitHub.
Python – Sys Module
Python sys module is an essential module that stores the command line arguments into a list structure; we could access it with sys.argv. It is quite similar to the C library using argc/argv to access the arguments. It is a useful and straightforward way to read the PATH variable and the command-line arguments as String. Let us learn a number of the characteristics of the Python sys module.
Python sys.argv
This function of sys module returns a list of arguments passed to the Python script. The element at sys.argv[0] in the list is always Python script’s name. The remaining arguments sys.argv[1] to sys.argv[n] are saved at the following indices. As a delimiter between arguments, space is utilized. Argument values which contain space inside need to be quoted.
Here is a Python script (demo.py), using two command-line arguments.
Example: demo.py import sys print("Hello {}. Welcome to {} 3".format(sys.argv[1], sys.argv[2]))
Above script is executed from the command-line as follows:
C:\python> python demo.py Thakur Python Hello Thakur. Welcome to Python 3
As seen above, sys.argv[1] contains the first parameter ‘Thakur’, while sys.argv[2] contains the second parameter ‘Python’. sys.argv[0] contains the script file name demo.py.
Python sys.exit
This function of sys module causes the script to return to either the Python console or the command prompt. It used to exit the program in case of a generation of an exception safely.
Syntax:
sys.exit()
Example:
import sys print("Python") sys.exit(1) print("Tutorial") Output: Python
As you can seen in above example, as soon as the sys.exit(1) function is encountered, it terminate the execution of the script. Thus, “Tutorial” doesn’t get printed in the output.
Python sys.maxsize
This function returns the largest integer with maximum value a variable can take and store in a Python script.
Syntax:
sys.maxsize
Example:
import sys sys.maxsize
Output:
C:\user\thakur\Python\dummy.py 9223372036854775807 Process finished with exit code 0
Python sys.path
This is an environment variable that displays the PATH for all Python modules.
Syntax:
sys.path
Example:
import sys sys.path
Output:
['','C:Python38-32\python36.zip','C:\Python38-32\DLLs','C:\Python38-32\lib','C:\Python38-32', 'C:\Python38-32\lib\site-packages']
Python sys.version
This function returns the version number of the current Python interpreter.
Syntax:
sys.version
Example:
import sys sys.version Output: '3.7.0 (v4.6.0:f63c2622b4, Jul 23 2020, 15:00:18) [MCD v.1500 64 bit (AMD64)]'
Python getopt module
The Python getopt module is quite similar in functioning as the C getopt() function for parsing command-line parameters.
The Python getopt module is useful in parsing command-line arguments where we all need users to input some choices. It is, generally, used for parsing an argument sequence like sys.argv. To put it differently, this module helps scripts to parse command-line arguments in sys.argv.
Python argparse module
Python argparse module is the preferred way to parse command line arguments. Parsing arguments is a prevalent task, which Python scripts perform and act based on the passed values. It’s quite common to this getopt module, but that’s somewhat complex and typically need more code to the same job.