Python Command Line Arguments with sys.argv – POFTUT

Python Command Line Arguments with sys.argv


Python scripts can be run in different ways. Python interpreter can be used to file python scripts but it is not so practical. Also, scripts are not saved. After the interpreter is closed or written code will be lost. The most popular usage to write and run python scripts is creating a python script file and running it. Passing parameters or options to the script is very useful. There is two popular way to pass command-line arguments to the python.

  1. Getopt Module
  2. Argparse Module

We will look in details to these modules below.

Getopt Module

Getopt module is a python module that can be loaded with import sys . This module provides command-line arguments as an array.

#!/usr/bin/python3 
import sys 
 
print(sys.argv)
Getopt Module
Getopt Module

As we can see there is an empty list normally it contains provided arguments as list elements. Save this script to the file pythoncommandlineargument.py .Make python script file executable like below.

$ chmod u+x pythoncommandlineargument.py

And we can run python script by providing arguments.

$ ./pythoncommandlineargument.py a1 a2 a3

As we see sys.argv provides arguments as a list. The first element of the list is the script name and others are arguments provided. We can easily get whatever we want just providing the index of the list like below.

sys.argv[1]

#a1

Argument Length

We can get provided argument list length like below.

#!/usr/bin/python3 
import sys 
 
print(len(sys.argv))

And we run our script again with arguments

$ ./pcla.py a1 a2 a3

ArgParser

ArgParser is used to show the argument menu and parse provided argument according to the menu. This module is used to create more user-friendly menus.

#!/usr/bin/python3 
import argparse 
 
parser = argparse.ArgumentParser(description='This is a example') 
parser.add_argument('-i','--input', help='Set Input',required=True) 
args = parser.parse_args() 
 
print(args.input)
  • Description can be provided with description=’This is a example’
  • Arguments are added with add_argument where -i is short –input is a long specifier
  • Help about the specified argument is provided with help=’Set Input’
ArgParser
ArgParser

List and Print Arguments Help Menu

We will run like regular Linux tools with the -h option which will print required arguments and their input names both short and long format. We run our script by providing -h to get help menu.

$ ./pcla.py -h
List and Print Arguments Help Menu
List and Print Arguments Help Menu

Get Provided Argument

We can also parse given argument with -i like below. We can get provided argument by getting input from the parser.

$ ./pcla.py -i a1

LEARN MORE  How To Download, Install, and Use Python Idle Editor?

Leave a Comment