Obtain command line parameters in Python

Source: Internet
Author: User

Sys. argv []

 

List of strings containing command line parameters. Obtain the parameters by subscript.

 

For example:

 

#!/usr/bin/python# Filename: using_sys.py  import sys  print 'The command line arguments are:'for i in sys.argv:    print i  print '\n\nThe PYTHONPATH is', sys.path, '\n'print argv[1]

argv[0] Indicates the file path. Of course, agv [] can also store multiple values.

Getopt

 

Used to extract command line options and parameters, that is, sys. argv. The command line option makes program parameters more flexible. The short and long options modes are supported.

 

import getopt#python scriptname.py -f 'hello' --directory-prefix=/home -t --form    at 'a' 'b'shortargs = 'f:t'longargs = ['directory-prefix=', 'format', '--f_long=']opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )

 

The format of the getopt function is getopt. getopt ([command line parameter list], "short options", [long Option List]).
The colon (:) after the short option name indicates that this option must have additional parameters.
The equal sign (=) after the long option name indicates that this option must have additional parameters.
Returns opts and args.

 

Opts is a parameter option and its value tuples ('-F', 'Hello'), ('-t', ''), ('-- format ', ''), ('-- directory-prefix','/home '))

 

Args is a command line input ('A', 'B') that removes useful parameters ')

 

Then, you can retrieve all the command line options and their corresponding parameters by traversing opts.

 

You can retrieve the options and parameters of all commands by traversing opts,

 

for opt, val in opts:    if opt in ( '-f', '--f_long' ):        pass    if ....

 

Analyze different promotional item parameters for different processing. Generally, the option parameter list is printed as a help option.


The typical use of getopt is also provided in python Documentation:

import getopt, sysdef main():    try:        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])    except getopt.GetoptError, err:        # print help information and exit:        print str(err) # will print something like "option -a not recognized"        usage()        sys.exit(2)    output = None    verbose = False    for o, a in opts:        if o == "-v":            verbose = True        elif o in ("-h", "--help"):            usage()            sys.exit()        elif o in ("-o", "--output"):            output = a        else:            assert False, "unhandled option"    # ...if __name__ == "__main__":    main()
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.