Python command line arguments Tutorial

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.

python command line arguments example

Python command line arguments

  1. You can set up help messages and documentation for command line arguments
  2. Set default values for arguments in a clean and readable way
  3. Have a set number of options for a particular command line argument
  4. Automatic type conversion on input
  5. It supports a variable number of parameters for a single argument
  6. It can automatically apply an action or function to your input, as specified by you

 

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

Use of command line arguments:-

The command line will give program different input on fly and without changing the code.
This command line argument is similar to function parameter and declared as programming language.
The command line will help to keep the program in generic nature.
After writing the program in CSV file then it will pass name from the command line then the program will work for CSV.
The next benefit is security which comes with it as we save program data into the database.
While creating the complex command line program is needed for the configuration of the file.
While using specify configuration file it has good idea to accept the values by creating the command line interference with python as argparse library.

The modules are as follow:-

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 python command line argument with the language:-

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,

  1. Len(sys.argv) this is the number of command-line argument.
  2. Sys.argv is a list of command line argument.
  3. Sys, argv [0] is program i.e. the script name.

Parameters:-

  1. arg:-

          This is the argument list to be parsed with.

  1. Long_options:-

          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.

  1. 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)

Python command line arguments Example :-

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
$

Python getopt module:-

            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)

Python getopt module Example

import getopt
import sys
argv=sys.argv [1:]
opts, args=getopt.getopt (argb,’x: y :’)
print(f‘OptionsTuple is {opts}’)
print(f’Additional Command-line argument list is {args}’)

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’]
$

Python argparse module:-

 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,

  1. It will allow the use of positional argument
  2. This will support variable numbers of parameters for a single option.
  3. Allow the customization of prefix chars.
  4. It supports subcommands like a main command-line parser and uses other command line parser which depends on some argument.

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

Code is:-

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 “

Python argparse module Example:-

import argparse
parser=argparse.ArgumentParser ()
parser.add_argument (“language”)
parser.add_argument (“name”)
args=parser.parse_arg ()
if args.langugae==’Python:’
print(“I love Python too”)
else:
print(“Learn Python, you will like it”)
print(f’Hello {args.name}, this was a simple introduction to argsparse module’)

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
$

Advantages of command-line arguments in python:-

  1. The command line is much easier and faster to use for expert but not possible for beginner.
  2. This can be used with greater ease then GUI, remote GUI.
  3. In the complex task command line can be scripted to automate the things.

Disadvantages of command-line arguments in python:-

    • There are some things which are hard or impossible to do on the command line as graphics and surfing the web.
    • Manny peoples are learning and remembering the commands in hard unless they use the command all the time.
Additional Services : Refurbished Laptops Sales, Python Classes, Share Market Classes And SEO Freelancer in Pune, India