Python command line arguments example include sys.argv, getopt and argparse. The argparse is used and best command argument in Python due to its specialty it is commonly used. The Command-line arg is given to the program and also get the additional information for the program to execute. The command-line is present in the programs according to the needs as every program do not have command line. We should start the program with additional argument and the arguments are passes into the program. The Python programming will start with the command line argument.
The python using the raw_input () or input ().There is another method uses command line argument.
The use of the command line argument is as the modules to get an argument.
In command line argument the program will take any number of command lines and types.
Example explanation:-
If monkey is the name of actual command and shell is executed then command at shell prompt. So the command line becomes,
Monkey-name of command is executed
Everything on the command-line is taken as argument to command
The total number of command-line argument is passed including the command name as 2.
Command |
Command name |
Total number of arguments |
Arguments |
Ls/etc/resolve.conf |
ls |
1 |
/etc/resolve.conf |
ls |
ls |
0 |
None |
Grep—colorroot/etc/passwd |
grep |
2 |
-cplor,root,/etc/passwd |
Module |
uses |
Python version |
docopt |
Creating a command line interface |
>=2.3 |
sys |
All argument in sys.argv |
All |
argparse |
We have to build a command line interface |
>=2.3 |
fire |
It is automatically generating the command line arguments |
All |
optparse |
Deprecated |
<2.7 |
The command-line argument has different ways for handling the command lines of argument.
1. Sys module:-
The sys module is direct to the c library and second way tp getopt module and handles both short and long options.
The next way is the argparse which delivers the optparse module.
The command-line argument is the input when executing them and all programming languages.
The command line is set for the specific option for the program.
The basic module is shipped with python distribution from the early days.
It is the same as c library using argv to access the arguments.
The sys module is implemented by command line argument in simple name as sys.argv.
Accessing command line arguments:-
The sys model serves by two purposes as,
Parameters:-
This is the argument list to be parsed with.
It is an optional parameter and list of the string with the name of long options which is supported.
Long options will require the argument followed by equal sign and accept only options.
The string is an optional letter that script to recognize and require an argument that is followed by a colon.
Code is:-
Import sys
Print(type (sys.argv))
Print(‘the command line argument is :’)
For I in sys.argv:
Print(i)
Import sys
If len (sys.argv)! =2:
raise ValueError (‘please provide email-is to send the email.’)
print(f’ScriptName is {sys.argv [0]}’)
email=sys.argv [1]
print (f’sending test email to {email}’)
Output:-
Python 3.7 command-line-args, py test@askpython.com
Script Name is command-line-args.py
Sending test email to test@askpython.com
$python 3.7 command-line-args.py
Traceback (most recent call last):
File”Command-line-args.py”, line4, in<module>
raiseValueError (‘please provide email-is to send the email.’)
ValueError: please provide email-id to send the email
$
The getopt module is similar in working as c function and the parsing command line parameters.
The getopt is used for parsing the command line argument where we want to enter some of the options.
The getopy module extends the separation of inputting stringy parameters and validation.
The getopt function will allow short and the long options including value assignment.
Code:-
import getopt
import sys
argv=sys.argv [1]
Try:
Opts, args=getopt.getopt (argv,’hm: d’, [‘help’,’my_file=’])
print(opts)
print(args)
except getopt.GetoptError:
Print(‘something went wrong!’)
Sys.exit(2)
Output:-
$python 3.7 command-line-args.py -x1-y2AB
Options Tuple is [(‘-x’,’1’, (‘-y’,’2’)]
Additional command-line argument list is [‘A’,’B’]
$
This module is used to parse the command line arguments.
It will provide a lot of options such as default value, help msg, the data type of argument etc.
The python will support the creation of programs that run on the command-line.
Use of this module is to parse command line argument and have many options with the argparse module as,
The command line will offer standard output with the solutions.
Argparse will allow verification of fixed and optional argument with a name as either UNIX, or GNU style.
This will provides a lot of options as a positional argument and default value for argument and help message and specify data type of the argument.etc.
The execution of python language is given as follows,
$python commands.py inp1inp2inp3
import sys, getopt
def main (argv):
inputfile=”
outputfile=”
try:
opts, arg=geyopt.getopt (argv,”hi: o”, [“ifilae=”,”ofile=”])
except getopt.GetoptError:
print ‘test.py-i<inputfile>-o<outputfile>’
sys.exit (2)
for opt.arg in opts:
if opt==’-h’:
print’test.py -i<inputfile>-o<outputfile>’
sys.exit ()
elif opt in (“-i”,”--ifile”):
inputfile=arg
elif opt in (“-o”,”--ofile”):
outputfile=arg
print’Input file is “’,inputfile
print’Output file is “’,Outputfile
if_name_==”_main_”:
main (sys.argv [1 :])
Output:-
$ test.py –h
Usage: test.py –i<inputfile>-o<output file>
Usage: test.py –I BMP –o
Usage: test.py –i<inputfile>-o<outputfile>
$ test.py –I inputfile
Input file is”inputfile
Output file is “
Output:-
$python 3.7 command-line-args.py Python David
I love python too
Hello David, this was simple introduction to argpasrse module
$
$Python 3.7 command-line-args.py-h
Usage: command-line-args.py [-h] language name
Positional arguments:
Language
Name
Optinal arguments:
-h,--help show this message and exit
$