There are different ways to run a Python script. One of them is using the command line. To interact with the program when running the script you can use command line arguments. In this article, we will show how to pass arguments to a Python script and how to process them.
Table of Contents
What are command line arguments?
Command line arguments are specific information passed to the program when it is started. For example, if the program needs to output data to a file, you can pass it as a command line argument instead of hardcoding it. A program can have one or more command-line arguments.
Why do we need to use command line arguments?
We can use command-line arguments to interact with the program in a GUI-like manner. Using them, we can transfer important information to the program, easily configure it, change its behavior, and experiment with how the program will work with different values of the arguments.
How to pass arguments to a Python script?
When running a Python script, command-line arguments are passed after its name. This example runs the Python script “test.py”, which has two command-line arguments: arg1 and arg2.
1 |
python test.py arg1 arg2 |
How to parse Python command line arguments?
There are several ways for parsing command-line arguments in Python.
You can use the sys module to pass arguments to a Python script
This is a basic Python module that implements command-line arguments in a simple sys.argv list structure and provides access to any command-line argument.
The first command line argument in the list, sys.argv[0], is the Python script name. The rest of the list items are command-line arguments. Each element contains one argument. In order to get the number of elements in the list, you need to use the len(sys.argv) command.
Let’s consider the following example.
1 2 3 4 5 |
import sys print 'Number of arguments:', len(sys.argv) - 1 print 'Script name:', sys.argv[0] print 'Argument List:', str(sys.argv[1:]) |
This script prints the number of Python command line arguments, the name of the program, and the list of arguments. Save it to a file called “test.py” and run it using the command:
1 |
python test.py arg1 arg2 arg3 |
The result of executing the script will be as follows:
1 2 3 |
Number of arguments: 3 Script name: test.py Argument List: ['arg1', 'arg2', 'arg3'] |
The getopt module is used when we pass arguments to a Python script
The getopt Python module allows you to parse command line options and argument values. For this, the getopt() method is used, which has the following parameters:
- args is a list of command line arguments.
- short_options are the option letters to be recognized. If the parameter needs to be assigned a value, then a colon ‘:’ is placed after it.
- long_options is a list of long option names to support. These are optional arguments.
The getopt.getopt() method returns two elements:
- A list of (option, value) pairs.
- The list of program arguments remains after removing the parameter list.
Consider the following script.
1 2 3 4 5 6 7 8 9 10 11 |
import getopt, sys arguments = sys.argv[1:] options, values = getopt.getopt(arguments, "hi:o:", ["in=","out="]) for opt, val in options: if opt in ("-h", "--help"): print ("Displaying help") elif opt in ("-i", "--ifile"): print "Input file:", val elif opt in ("-o", "--ofile"): print "Output file:", val |
This script can take three arguments on the command line: -h (used to display help), -i or –ifile (input file), -o or –ofile (output file).
The result of running the script:
1 2 3 4 5 6 |
python test.py -h Displaying help python test.py -i in Input file: in python test.py -o out Output file: out |
Parse commands with the argparse module when we need to pass arguments to a Python script
This module offers a convenient command line interface. It allows the program to specify the necessary arguments and gets them from sys.argv itself.
Below is an example of how to use argparse module to accept a name parameter.
1 2 3 4 5 6 7 8 |
import argparse parser = argparse.ArgumentParser() parser.add_argument("-n", "--name") args = parser.parse_args() print"name=", args.name |
How to use PyScripter for creating Python scripts?
PyScipter is a fast powerful free Python IDE. It has a user-friendly interface and offers many features that greatly simplify the process of developing in Python:
- Code editor with syntax highlighting.
- Built-in Python interpreter with debugging, editor views, and code exploration.
- The ability to use drag-and-drop operations for editing, context indentation, curly bracket highlighting, and syntax highlighting.
- Check syntax as you type.
- Ability to create templates by saving layouts with specified names.
- Automatic code completion.
- Ability to run created programs in different ways.
- The ability to track the history of teams.
Install PyScipter and appreciate the benefits it provides for creating and running Python scripts.
FAQ
How do you pass arguments to a Python script?
To pass arguments to the Python script, you need to use the command line and specify the necessary arguments after the name of the script file.
How do you pass multiple arguments to a Python script?
You need to specify the required number of parameters in the function definition. When running a script, list all the arguments one by one after the script name.
How many arguments can be passed to a Python script?
There is no limit to the number of arguments that can be passed to a function when it is called. So you can use as many arguments as you need.
What are the 4 types of arguments in Python?
- Default arguments are arguments that have a default value that is used if no other value has been passed to the function.
- Keyword (named) arguments are arguments whose value is assigned by their name. When a function is called, not only the value of the argument should be passed, but its name, the ‘=’ assignment sign, and the value.
- Positional arguments are arguments whose values are assigned based on their position when the function is called. For example, the first positional argument must come first when calling a function. By default, Python functions use positional arguments.
- Arbitrary arguments. They are used when it is not known in advance how many arguments need to be passed.
How to give input to a Python script from command line?
Use the input() function to get the string or number that the user has entered.