2011-8-23

Python 里边的parser用法

15.5. optparse — Parser for command

line options

http://docs.python.org/library/optparse.html

Here’s an example of using optparse in a simple script:

from optparse import OptionParser

[...]

parser = OptionParser()

parser.add_option("-f", "--file", dest="filename",

help="write report to FILE", metavar="FILE")

parser.add_option("-q", "--quiet",

action="store_false", dest="verbose", default=True,

help="don't print status messages to stdout")

(options, args) = parser.parse_args()

With these few lines of code, users of your script can now do the “usual thing” on the command-line, for example:

--file=outfile -q

Thus, the following command lines are all equivalent to the above example:

-f outfile --quiet

--quiet --file outfile

-q -foutfile

-qfoutfile

Additionally, users can run one of

-h

--help

and optparse will print out a brief summary of your script’s options:

Usage: [options]

Options:

-h, --help            show this help message and exit

-f FILE, --file=FILE  write report to FILE

-q, --quiet           don't print status messages to stdout

where the value of yourscript is determined at runtime (normally fromsys.argv[0]).

15.5.1.1. Terminology

argument

a string entered on the command-line, and passed by the shell to execl() orexecv(). In Python, arguments are elements of sys.argv[1:] (sys.argv[0] is the name of the program being executed). Unix shells also use the term “word”.

It is occasionally desirable to substitute an argument list other thansys.argv[1:], so you should read “argument” as “an element of sys.argv[1:], or of some other list provided as a substitute for sys.argv[1:]“.

option

an argument used to supply extra information to guide or customize the execution of a program. There are many different syntaxes for options; the traditional Unix syntax is a hyphen (“-“) followed by a single letter, e.g. -x or -F. Also, traditional Unix syntax allows multiple options to be merged into a single argument, e.g. -x -F is equivalent to -xF. The GNU project introduced -- followed by a series of hyphen-separated words, e.g.--file or --dry-run. These are the only two option syntaxes provided byoptparse.

Some other option syntaxes that the world has seen include:

·   a hyphen followed by a few letters, e.g. -pf (this is not the same as multiple options merged into a single argument)

·   a hyphen followed by a whole word, e.g. -file (this is technically equivalent to the previous syntax, but they aren’t usually seen in the same program)

·   a plus sign followed by a single letter, or a few letters, or a word, e.g. +f, +rgb

·   a slash followed by a letter, or a few letters, or a word, e.g. /f,/file

These option syntaxes are not supported by optparse, and they never will be. This is deliberate: the first three are non-standard on any environment, and the last only makes sense if you’re exclusively targeting VMS, MS-DOS, and/or Windows.

option argument

an argument that follows an option, is closely associated with that option, and is consumed from the argument list when that option is. Withoptparse, option arguments may either be in a separate argument from their option:

-f foo

--file foo

or included in the same argument:

-ffoo

--file=foo

Typically, a given option either takes an argument or it doesn’t. Lots of people want an “optional option arguments” feature, meaning that some options will take an argument if they see it, and won’t if they don’t. This is somewhat controversial, because it makes parsing ambiguous: if -atakes an optional argument and -b is another option entirely, how do we interpret -ab? Because of this ambiguity, optparse does not support this feature.

positional argument

something leftover in the argument list after options have been parsed, i.e. after options and their arguments have been parsed and removed from the argument list.

required option

an option that must be supplied on the command-line; note that the phrase “required option” is self-contradictory in English. optparse doesn’t prevent you from implementing required options, but doesn’t give you much help at it either.

For example, consider this hypothetical command-line:

prog -v --report /tmp/report.txt foo bar

-v and --report are both options. Assuming that --report takes one argument,/tmp/report.txt is an option argument. foo and bar are positional arguments.

15.5.2. Tutorial

While optparse is quite flexible and powerful, it’s also straightforward to use in most cases. This section covers the code patterns that are common to any optparse-based program.

First, you need to import the OptionParser class; then, early in the main program, create an OptionParser instance:

from optparse import OptionParser

[...]

parser = OptionParser()

Then you can start defining options. The basic syntax is:

parser.add_option(opt_str, ...,

attr=value, ...)

Each option has one or more option strings, such as -f or --file, and several option attributes that tell optparse what to expect and what to do when it encounters that option on the command line.

Typically, each option will have one short option string and one long option string, e.g.:

parser.add_option("-f", "--file", ...)

You’re free to define as many short option strings and as many long option strings as you like (including zero), as long as there is at least one option string overall.

The option strings passed to add_option() are effectively labels for the option defined by that call. For brevity, we will frequently refer to encountering an option on the command line; in reality, optparse encounters option strings and looks up options from them.

Once all of your options are defined, instruct optparse to parse your program’s command line:

(options, args) = parser.parse_args()

(If you like, you can pass a custom argument list to parse_args(), but that’s rarely necessary: by default it uses sys.argv[1:].)

parse_args() returns two values:

options, an object containing values for all of your options—e.g. if --filetakes a single string argument, then options.file will be the filename supplied by the user, or None if the user did not supply that option

args, the list of positional arguments leftover after parsing options

This tutorial section only covers the four most important option attributes:action, type, dest (destination), and help. Of these, action is the most fundamental.

OK,that is enough for me to realize the GNU RADIO’s code. If I have extra time, I will continue to learn it.

python的parse用法_Python 里边的parser用法相关推荐

  1. python defaultdict 类属性_Python collections.defaultdict模块用法详解

    Python中通过Key访问字典,当Key不存在时,会引发'KeyError'异常.为了避免这种情况的发生,可以使用collections类中的defaultdict()方法来为字典提供默认值. 语法 ...

  2. python里apply用法_Python apply函数的用法

    Python apply函数的用法 发布于 2014-08-07 21:02:24 | 674 次阅读 | 评论: 0 | 来源: 网友投递 Python编程语言Python 是一种面向对象.解释型计 ...

  3. python中module用法_Python学习之module用法

    Python学习之module用法 Python学习之module用法 为什么80%的码农都做不了架构师?>>> Python has a way to put definition ...

  4. python中enumerate在for循环中用法_python中enumerate的用法实例解析

    在python中enumerate的用法多用于在for循环中得到计数,本文即以实例形式向大家展现python中enumerate的用法.具体如下: enumerate参数为可遍历的变量,如 字符串,列 ...

  5. python文件的用法_Python文件读写常见用法总结

    1. 读取文件 # !/usr/bin/env python # -*- coding:utf-8 -*- """ 文件读取三步骤: 1.打开文件 f=open(file ...

  6. python多态的例子_Python编程之多态用法实例详解

    本文实例讲述了Python编程之多态用法.分享给大家供大家参考.具体分析如下: 什么是多态?顾名思义,多态就是多种表现形态的意思.它是一种机制.一种能力,而非某个关键字.它在类的继承中得以实现,在类的 ...

  7. python写了代码_Python写代码的用法建议

    1.Mutable and immutable types Python有两种内置或用户定义的类型 可变类型是允许就地修改内容的类型.典型的可变列表是列表和词典:所有列表都有变异方法,如 list.a ...

  8. python datetime timedelta函数_Python Pandas DatetimeIndex.to_perioddelta()用法及代码示例

    Python是进行数据分析的一种出色语言,主要是因为以数据为中心的python软件包具有奇妙的生态系统. Pandas是其中的一种,使导入和分析数据更加容易. Pandas DatetimeIndex ...

  9. python断言assert实例_Python断言assert的用法代码解析

    在开发一个程序时候,与其让它运行时崩溃,不如在它出现错误条件时就崩溃(返回错误).这时候断言assert 就显得非常有用. python assert断言是声明布尔值必须为真的判定,如果发生异常就说明 ...

最新文章

  1. R语言stringr包str_detect函数检测字符串中模式存在与否实战
  2. 目前的计算机还没有实现真正的智能
  3. idea 升级到2020后 无法启动_启动崩盘!IDEA 2020 无法启动的解决办法|赠送 IDEA 2020 新功能...
  4. PYG教程【五】链路预测
  5. moment 时间格式化
  6. ApplicationContextAware
  7. dataframe两个表合并_R语言读取多个excel文件后合并:rbind/merge/cmd合并
  8. JAVA加密算法系列-AesCBC
  9. Unity上的Oculus Quset2开发(2) —— 在VR里打棒球
  10. LOOP AT GROUP语法熟悉
  11. 《指数基金投资从入门到精通》读书笔记
  12. 医院子母钟时钟系统可选方案
  13. Kali-linux-2020 sqli-labs环境配置(含网上最全Less-29在Kali上的配置)
  14. 5 款常用的 C++ 在线编译器推荐
  15. VScode直接执行ts文件
  16. 安装visio viewer2013成功后仍无法使用
  17. 23家上市公司抢先机落地区块链应用,政务、金融领域成果最吸睛
  18. 2019年上半年软件设计师下午试题
  19. Zeppelin-0.9.0同步Apache DS LDAP 方案
  20. MariaDB Galera Cluster 集群部署

热门文章

  1. Python3利用Twilio(国际)以及腾讯云服务(国内)免费发送手机短信
  2. 教你批量消除视频原声,一学就会
  3. 红队使用的那些工具(基础篇)附下载
  4. FTP工具,3款FTP工具推荐
  5. 时间序列预测--ARIMA、LSTM
  6. 苹果电脑拷贝文件到u盘很慢_ChronoSync v4.9.1 一款文件资料数据云同步备份工具...
  7. android 天气 没有广告,收集几款无广告的纯净天气App
  8. python怎么加字幕_python3实战之字幕vtt与字母srt的相互转换
  9. python建站部署_记录一下自己的建站过程(四)MongoDB与Pymongo
  10. wap论坛php源码,家教平台教育论坛相关网站PHP源码+WAP手机端自适应