Reading Command Line Arguments In Python

Discussion in 'Python' started by pradeep, Sep 26, 2012.

  1. pradeep

    pradeep Team Leader

    Apr 4, 2005
    Likes Received:
    Trophy Points:
    Kolkata, India
    Home Page:
    Command line arguments are quite old, in the days of DOS they were generally just options enabling/disabling mechanism and were known as switches. But, after the growth of *nix systems command line arguments have been developed and have provided a lot of features to power users.

    Here's an example of a command line argument.

    [pradeep@home-desktop]$ ls -lh --color='yes'
    Now, you can pass switches, values, single & multiple, it does not always need to be in a specific order, you can pass multiple arguments at once. There are two types of options, short options (are single characters), like l & h in the above sample, and long options (are more than 1 character) which are preceded by 2 hipens (-).

    In this article we'll be looking at making your Python program read command line arguments.


    To learn about reading command line parsing, let's first look at how Python reads command line arguments natively, it needs to be in a specific order as there is no parsing as such, just arguments that were passed from the shell. Follow the example below.

    import sys
    print 'Passed', len(sys.argv), 'arguments'
    print 'Arguments -', str(sys.argv)
    [pradeep@home-desktop ]$ /var/www/test/ Pradeep Partha
    Passed 3 arguments
    Arguments - ['/var/www/test/', 'Pradeep', 'Partha']

    Using getopt

    getopt module parses the command line arguments and processes them using the config that is provided to it. getopt accepts 3 arguments, first a list of arguments that need to be parsed, next is the list of options that need to be looked for, if an option should accompany a value it should be followed by : symbol (like in the example below, option i can have a value, whereas others are just switches), and the last optional parameter is long options for the previously specified short option, they should be specified in the same order as the short options. Try the example below:

    import sys,getopt
    opts, args = getopt.getopt(sys.argv[1:], 'ai:d', ['all','input=','debug'])
    for opt, arg in opts:
       print opt,"==>",arg
    [pradeep@home-desktop ]$ -i pradeep.txt -d --all
    -i ==> pradeep.txt
    -d ==>
    --all ==>
    In your code you can iterate the options parsed by getopt to change the behaviour of the program as per your needs.
    jsmartin and shabbir like this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice