Python uses getopt to get configuration parameters

Source: Internet
Author: User

In the project, especially a slightly larger project will basically use the configuration, will involve the configuration file read, configuration parameters read.

The common parsing configuration file is Configparser, and the parse command-line argument is getopt.

The parameters of getopt can be divided into two types: Long mode and short mode.

The long mode is:--arg1 arg_value on the command line.

Short mode is a common space-delimited parameter outside of the long mode.

Use the getopt.getopt () object in your program to get the parameter in the format:

opts, args = Getopt.getopt (arg_list, Shor_mode, Long_mode).

Arg_list in Python is sys.argv[1:] because we do not use filenames as parameter resolution.

In the returned result, opts is a list of parameter tuples, such as: [(--config_file, Config.ini)], and args is the argument list.

Chestnuts:

#!/usr/bin/python#-*-coding:utf-8-*-import getoptimport sysif __name__ = = ' __main__ ':    long_opts = ["config_file=" , "key1=", "key2="]    short_opts = ""    opts, args = Getopt.getopt (sys.argv[1:], short_opts, long_opts)    Config_ File = None    for opt in opts:        print opt[0], opt[1]    print args# command line execution macbook-pro:python$ python test_getopt.py- -config_file config.ini--key1 value1--key2 value2 args1 args2--config_file config.ini--key1 value1--key2 value2[' args1 ', ' ARGS2 ']

Python uses getopt to get configuration parameters

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.