Python command-line parameter parsing example application __python

Source: Internet
Author: User
one, sys.argv[]A list of strings containing command-line arguments to get parameters by subscript.
For example:
#!/usr/bin/python
# Filename:using_sys.py
Import Sys

print ' command line arguments are: '
For I in SYS.ARGV:
Print I

print ' \n\nthe pythonpath is ', Sys.path, ' \ n '
Print Argv[1]

Argv[0] Represents the path of the file itself. Of course, agv[] can also hold multiple values
Second, getoptUsed to extract command-line options and parameters, which is sys.argv.
command-line options make the program more flexible in its parameters. Supports short option mode and long option mode.

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 argument list], short option, [Long option list])
The colon after the short option name (:) indicates that the option must have additional parameters.
The equal sign (=) after the long option name indicates that the option must have additional parameters.
Return to opts and args.

OPTs is a tuple of parameter options and their value ('-f ', ' Hello '), ('-t ', ', '), ('--format ', '), ('--directory-prefix ', '/home '))
Args is a command line input other than a useful parameter (' A ', ' B ')
Then traverse opts to get all the command-line options and their corresponding parameters.

Traversal opts can get the options and parameters of all commands,
For opt, Val in opts:
If opt in (' f ', '--f_long '):
Pass
If .....


Analyze different parameters and do different processing. Generally, the list of option arguments is printed as a help option.
The typical use of getopt is also given in the Python documentation:Import getopt, sys

def 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) # 'll 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 ()
Iv. Example ApplicationA simple example is shown below:
Import getopt, sys


opts, args = Getopt.getopt (sys.argv[1:], "Hi:o:", ["Help", "input=", "output="])


def usage ():
Print Sys.argv[0] + '-I inputfile-o outputfile '
Print Sys.argv[0] + '-h #get help Info '


Input_file, output_file = ', '
For OP, value in opts:
If op = = ' I ' or op = '--input ':
Input_file = value
Elif op = = ' O ' or op = '--output ':
Output_file = value
Elif op = = '-h ':
Usage ()
Sys.exit ()


You can run on the command line in the following ways:
$ python test.py-i./input.txt-o./output.txt
$ python test.py--input=./input.txt-o./output.txt
$ python test.py-i./input.txt--output=./output.txt
$ python test.py--input=./input.txt--output=./output.txt
$ python test.py-h

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.