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

查看:21
本文介绍了如何在 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?

我明白,例如,如果我需要找出调试"是否在参数之间传递,它会是这样的:

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?

所有这些都是预期的调用:

All those are expected calls:

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

...第一个 - 因为不止一个数字"参数;第二个——因为……好吧,出乎意料的争论;第三和第四 - 因为非 3 位参数.

...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'

编辑:这是一个 optparse 示例,因为很多人在回答 optparse 时没有真正解释原因,也没有解释您必须进行哪些更改才能使其工作.

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天全站免登陆