如何在Python中处理命令行参数?

时间:2022-03-15 03:55:41

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?

如果我期望的是001或999(让我们把期望限制在001),那么处理命令行参数的简单表达式是什么?这一次999的范围),并且很少有其他的争论通过,并且愿意忽略任何意外?

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

How to find out if 009 or 575 was passed?

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

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

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

…第一个,因为不止一个“数字”参数;第二,因为……意想不到的参数;第三和第四,因为非三位数的争论。

5 个解决方案

#1


31  

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

正如其他人所回答的那样,optparse是最好的选择,但是如果您只是想要快速代码,可以尝试如下方法:

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: 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的主要原因是它为以后的扩展提供了更大的灵活性,并且在命令行上提供了更多的灵活性。换句话说,您的选项可以以任何顺序出现,并且使用消息是自动生成的。然而,要使它与optparse一起工作,您需要在可选参数前面修改您的规范以“-”或“-”,您需要允许所有的参数以任何顺序排列。

So here's an example using optparse:

这里有一个使用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'

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

与optparse和你的规范的不同之处在于,现在你可以有如下命令行:

python script.py --debug --xls 001

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

您可以通过调用parser.add_option()来轻松添加新的选项

#2


15  

Have a look at the optparse module. Dealing with sys.argv yourself is fine for really simple stuff, but it gets out of hand quickly.

看一下optparse模块。处理系统。argv本身对非常简单的东西很好,但是它很快就会失控。

Note that you may find optparse easier to use if you can change your argument format a little; e.g. replace debug with --debug and xls with --xls or --output=xls.

注意,如果您可以稍微更改您的参数格式,您可能会发现optparse更容易使用;用-xls或-output=xls替换debug和xls。

#3


2  

optparse is your best friend for parsing the command line. Also look into argparse; it's not in the standard library, though.

optparse是解析命令行的最好的朋友。也看着argparse;但它不在标准库中。

#4


2  

If you want to implement actual command line switches, give getopt a look. It's incredibly simple to use, too.

如果您想要实现实际的命令行开关,请给getopt看一看。使用起来也非常简单。

#5


0  

Van Gale is largely correct in using the regular expression against the argument. However, it is NOT absolutely necessary to make everything an option when using optparse, which splits sys.argv into options and arguments, based on whether a "-" or "--" is in front or not. Some example code to go through just the arguments:

在使用正则表达式的时候,Van Gale基本上是正确的。然而,在使用optparse时,并不是绝对必要的。基于“-”或“-”是否在前面,argv进入选项和参数。一些示例代码只讨论参数:

import sys
import optparse

claParser = optparse.OptionParser()
claParser.add_option(
(opts, args) = claParser.parse_args()
if (len(args) >= 1):
  print "Arguments:"
  for arg in args:
    print "  " + arg
else:
  print "No arguments"
sys.exit(0)

Yes, the args array is parsed much the same way as sys.argv would be, but the ability to easily add options if needed has been added. For more about optparse, check out the relevant Python doc.

是的,args数组的解析方式与sys相同。argv将会是,但是如果需要的话,可以轻松添加选项。有关optparse的更多信息,请查看相关的Python文档。

#1


31  

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

正如其他人所回答的那样,optparse是最好的选择,但是如果您只是想要快速代码,可以尝试如下方法:

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: 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的主要原因是它为以后的扩展提供了更大的灵活性,并且在命令行上提供了更多的灵活性。换句话说,您的选项可以以任何顺序出现,并且使用消息是自动生成的。然而,要使它与optparse一起工作,您需要在可选参数前面修改您的规范以“-”或“-”,您需要允许所有的参数以任何顺序排列。

So here's an example using optparse:

这里有一个使用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'

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

与optparse和你的规范的不同之处在于,现在你可以有如下命令行:

python script.py --debug --xls 001

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

您可以通过调用parser.add_option()来轻松添加新的选项

#2


15  

Have a look at the optparse module. Dealing with sys.argv yourself is fine for really simple stuff, but it gets out of hand quickly.

看一下optparse模块。处理系统。argv本身对非常简单的东西很好,但是它很快就会失控。

Note that you may find optparse easier to use if you can change your argument format a little; e.g. replace debug with --debug and xls with --xls or --output=xls.

注意,如果您可以稍微更改您的参数格式,您可能会发现optparse更容易使用;用-xls或-output=xls替换debug和xls。

#3


2  

optparse is your best friend for parsing the command line. Also look into argparse; it's not in the standard library, though.

optparse是解析命令行的最好的朋友。也看着argparse;但它不在标准库中。

#4


2  

If you want to implement actual command line switches, give getopt a look. It's incredibly simple to use, too.

如果您想要实现实际的命令行开关,请给getopt看一看。使用起来也非常简单。

#5


0  

Van Gale is largely correct in using the regular expression against the argument. However, it is NOT absolutely necessary to make everything an option when using optparse, which splits sys.argv into options and arguments, based on whether a "-" or "--" is in front or not. Some example code to go through just the arguments:

在使用正则表达式的时候,Van Gale基本上是正确的。然而,在使用optparse时,并不是绝对必要的。基于“-”或“-”是否在前面,argv进入选项和参数。一些示例代码只讨论参数:

import sys
import optparse

claParser = optparse.OptionParser()
claParser.add_option(
(opts, args) = claParser.parse_args()
if (len(args) >= 1):
  print "Arguments:"
  for arg in args:
    print "  " + arg
else:
  print "No arguments"
sys.exit(0)

Yes, the args array is parsed much the same way as sys.argv would be, but the ability to easily add options if needed has been added. For more about optparse, check out the relevant Python doc.

是的,args数组的解析方式与sys相同。argv将会是,但是如果需要的话,可以轻松添加选项。有关optparse的更多信息,请查看相关的Python文档。