Python command-line arguments and getopt modules

Source: Internet
Author: User
Tags function prototype parse string

Sometimes we need to write some scripts to handle some tasks, it is often necessary to provide some command line parameters, according to different parameters for different processing, in Python, command line parameters and C language very similar (because standard Python is implemented in C language). In C, the main function of the prototype is int main (int argc, char **argv), here mainly refers to the Linux platform, ARGC refers to the command line passed in the number of parameters (the name of the program is the first parameter), and argv is an array of pointers, Each element is a pointer to a command-line argument. Command-line arguments in python are stored in sys.argv, argv is a list, and the first element is the program name.

Look at the following example:

test.py

#-*-coding:utf-8-*-import sys' __main__ ':        print i  
run at the command line./test.py 1 2 3, the results are as follows:

test.py

1

2

3

In this way, the command-line arguments can be judged to perform different actions.
Python's standard library actually has a getopt module that specifically handles command-line arguments, which provides 2 functions and a class, and we mainly use the getopt function, which looks at the function prototype first:
Def getopt (args, shortopts, longopts = []):
Let's look at an example first, and it will be easy to understand.

try:opts, args = getopt.getopt (Sys. Argv[ 1:],  "ho:", [ "help",  "output="]) except getopt. Getopterror: # print help information and exit: for name, value in opts: print name, Valuefor item in Args: print item            

1. The function used for processing is called getopt () because it is a getopt module that is imported directly using import, so it is possible to add a qualified getopt.
2. Use sys.argv[1:] to filter out the first parameter (it is the name of the execution script and should not be counted as part of the parameter).
3. Use the short format to parse the string "ho:". The option character is written in the parse string when an option simply represents a switch state, that is, when no additional parameters are followed. When an optional item is followed by an additional parameter, the Write option character in the parse string is appended with a ":" Number.  So "ho:" means "h" is a switch option; "O:" indicates that a parameter should be followed.
4. Use the long format to parse the list of strings: ["Help", "output="]. Long format strings can also have a switch state, which is not followed by the "=" number. If you follow an equal sign, you should have a parameter later.  This long format means "help" is a switch option; "Output=" indicates that a parameter should be followed.
5. Call the Getopt function. The function returns two lists: OPTs and args. OPTs the format information for the analysis. Args is the remaining command-line argument that is not part of the format information. OPTs is a two-tuple list. Each element is: (option string, additional parameter). Empty string If no additional parameters are available.
6. The entire process uses exceptions to include, so that when parsing errors, you can print out usage information to inform the user how to use the program.
as explained above, a command line example is:
'-h-o file--help--output=out file1 file2 '
after the analysis is complete, the OPTs should be:
[('-H ', '), ('-O ', ' file '), ('--help ', '), ('--output ', ' out ')]
and the args are:
[' file1 ', ' file2 ']
The following are processed according to different parameters:

In opts: in      ("--help"): Usage () sys.  In ("--output"): output = a   

Python command-line arguments and getopt modules

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.