Page Content

Posts

What Are Command-Line Arguments In Python With Example

Command-Line Arguments

Command-Line Arguments
Command-Line Arguments

Command-line arguments are inputs entered into a Python script from a command prompt or system shell at the moment of execution. They give a program access to data that can change with each run, increasing the general utility of scripts and reducing their dependency on interactive input or hardcoded values.

These arguments got their names in the past because, in text-based environments like Unix or DOS shells, they were entered on the command line next to the program name. Providing parameters in a separate window and passing them to the program as though they were executed from the command line is a common method to replicate this, even in contemporary Integrated Development Environments (IDEs) or Graphical User Interfaces (GUIs).

Similar to function arguments in functions, command-line arguments serve as a means of communicating with a program. They enable an administrator or program to execute a script with various behaviours without requiring human intervention; they are frequently utilised for automatic operations, such as nighttime batch jobs.

You must make use of the built-in sys module in order to access command-line parameters within a Python script. All of the command-line arguments are stored in a list named sys.argv that is provided by the sys module.

Structure of sys.argv

A list of strings makes up the sys.argv attribute. The name of the Python script that is being run is always the first member in this list, sys.argv. Index 1 (sys.argv) is where the user-supplied arguments begin. Including the script name, sys.argv shows all command-line arguments. Sys.argv.len returns the number of arguments.

Example: Accessing and Printing Command-Line Arguments

This straightforward Python script shows how to retrieve and output the command-line arguments that are sent to it:

# Program to Demonstrate Command Line Arguments in Python
import sys 
def main():
    # sys.argv prints all the arguments at the command line including file name 
    print(f"sys.argv prints all the arguments at the command line including file name {sys.argv}")
    # len(sys.argv) prints the total number of command line arguments including file name 
    print(f"len(sys.argv) prints the total number of command line arguments including file name {len(sys.argv)}")
    print("You can use for loop to traverse through sys.argv") 
    # A for loop can be used to traverse through each of the arguments in sys.argv 
    for arg in sys.argv: 
        print(arg) 

if name == "main": 
    main() 

This script defines a main function and imports the sys module. The full sys.argv list and its length are printed inside main, after which the list is iterated over and each argument is printed on a separate line. When the script is run directly, the if name == ” mai “: block guarantees that the main function is invoked.

Running the Script with Arguments

To run this script with command-line arguments, use the command line on your system (such as the terminal on Linux/macOS or the Command Prompt on Windows) to navigate to the directory where the script is saved, then type a command in the format python file name argument 1 argument 2 argument n. Spaces should be used to separate arguments.

For example, running Program 4.12.py from the command line looks like this: Python 4.12.py arg 1 2 3

Output:

['Program_4.12.py', 'arg_1', 'arg_2', 'arg_3']
4
Program_4.12.py
arg_1
arg_2
arg_3

As you can see, the script name is sys.argv (Program 4.12.py), and the arguments you supplied are the next items (arg 1, arg 2, arg 3).

Common Uses and Processing

Filenames, processing modes, flags, and other configuration options are frequently supplied to a script via command-line arguments. For example, rather than requesting the filename interactively using input(), a script that is intended to process a file may accept it as a command-line argument. This facilitates automating the script or integrating it with another software or a broader workflow.

In the sys argv list, arguments sent via the command line are always initially received as strings. The string arguments from sys argv must be explicitly changed to the proper data type (such as integer or float) if a script requires numerical input.

In simple situations, it may be sufficient to manually access sys argv elements by index (e.g., sys argv). To prevent errors in the event that the user does not supply the expected number of arguments, you should use len(sys argv) to verify the number of arguments before accessing items.

Manually parsing sys argv might get difficult for more complicated command lines with options (such as -i or -o followed by values) or numerous types of arguments. Modules created especially for processing command-line options and arguments are available in the Python standard library:

  • getopt: Based on the getopt() function in Unix.
  • Arg parse: A more recent, versatile, and typically more potent substitute.

You can handle changes in how they are presented, specify expected arguments and options, automatically produce help messages, do rudimentary validation, and convert types by using these modules. Defining arguments with descriptions and letting the module do the parsing is demonstrated in an example using arg parse. Iterating over sys.argv in search of pairs like “-name value” and putting them in a dictionary may be a straightforward example of manual parsing.

In conclusion, by supplying external inputs during execution, command-line arguments are an effective technique to increase the flexibility and reusability of Python scripts. The sys argv list, which contains the script name and the supplied arguments as strings, is how they are accessible. Direct access to sys.argv is feasible for simple scripts, but modules such as getopt or argparse provide strong parsing capabilities for more complicated requirements.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index