如何在Python中处理命令行参数? [英] How can I process command line arguments in Python?

查看:156
本文介绍了如何在Python中处理命令行参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我期望像001或999(我们将期望值限制在001 ... 999范围内)这个时候,处理命令行参数将是一个简单的表达式,并且几个其他参数传递,并希望忽略任何意外?

What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected?

我明白,如果我需要知道是否在参数之间传递debug,它会是这样:

I understand if for example I need to find out if "debug" was passed among parameters it'll be something like that:

if 'debug' in argv[1:]:
  print 'Will be running in debug mode.'

如何找出009或575是否通过?

How to find out if 009 or 575 was passed?

那些是预期的调用:

python script.py
python script.py 011
python script.py 256 debug
python script.py 391 xls
python script.py 999 debug pdf

这里我不在乎这样的调用:

At this point I don't care about calls like that:

python script.py 001 002 245 568
python script.py some unexpected argument
python script.py 0001
python script.py 02

...第一个 - 因为有多个数字参数;第二 - 因为...好,意想不到的争论;

...first one - because of more than one "numeric" argument; second - because of... well, unexpected arguments; third and fourth - because of non-3-digits arguments.

推荐答案

由于其他人回答,optparse是最好的选择,但如果你只需要快速代码尝试这样:

As others answered, optparse is the best option, but if you just want quick code try something like this:

import sys, re

first_re = re.compile(r'^\d{3}$')

if len(sys.argv) > 1:

    if first_re.match(sys.argv[1]):
        print "Primary argument is : ", sys.argv[1]
    else:
        raise ValueError("First argument should be ...")

    args = sys.argv[2:]

else:

    args = ()

# ... anywhere in code ...

if 'debug' in args:
    print 'debug flag'

if 'xls' in args:
    print 'xls flag'

EDIT :这里有一个轻松的例子,因为很多人都在回答简单,而没有真正解释为什么,或解释你必须改变,使其工作。

EDIT: Here's an optparse example because so many people are answering optparse without really explaining why, or explaining what you have to change to make it work.

使用optparse的主要原因是它为您以后的扩展提供了更多的灵活性,并且在命令行上给您更大的灵活性。换句话说,您的选项可以按任何顺序显示,并且使用消息会自动生成。但是要使它与optparse工作,你需要改变你的规格在可选参数前面加上 - 或 - ,你需要允许所有的参数以任何顺序。

The primary reason to use optparse is it gives you more flexibility for expansion later, and gives you more flexibility on the command line. In other words, your options can appear in any order and usage messages are generated automatically. However to make it work with optparse you need to change your specifications to put '-' or '--' in front of the optional arguments and you need to allow all the arguments to be in any order.

下面是一个使用optparse的例子:

So here's an example using optparse:

import sys, re, optparse

first_re = re.compile(r'^\d{3}$')

parser = optparse.OptionParser()
parser.set_defaults(debug=False,xls=False)
parser.add_option('--debug', action='store_true', dest='debug')
parser.add_option('--xls', action='store_true', dest='xls')
(options, args) = parser.parse_args()

if len(args) == 1:
    if first_re.match(args[0]):
        print "Primary argument is : ", args[0]
    else:
        raise ValueError("First argument should be ...")
elif len(args) > 1:
    raise ValueError("Too many command line arguments")

if options.debug:
    print 'debug flag'

if options.xls:
    print 'xls flag'

这里与optparse和你的规格的区别是现在你可以有命令行:

The differences here with optparse and your spec is that now you can have command lines like:

python script.py --debug --xls 001

,您可以通过调用parser.add_option()方便地添加新选项

and you can easily add new options by calling parser.add_option()

这篇关于如何在Python中处理命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆