简体   繁体   English

Python:optparse是否可以具有ACTION属性以像STORE和STORE_TRUE一样起作用?

[英]Python: Can optparse have the ACTION attribute to act both like STORE and STORE_TRUE?

I am using optparse to get command line input. 我正在使用optparse来获取命令行输入。

Lets say that I am running a script demo.py and it creates some output. 可以说我正在运行脚本demo.py并创建一些输出。 But unless I specify the command line input, the output is not written to a file. 但是,除非我指定命令行输入,否则输出不会写入文件。

I am trying to do the following: 我正在尝试执行以下操作:

python demo.py in command line should run the script, but not write the output anywhere. 命令行中的python demo.py应该运行脚本,但不要在任何地方写入输出。

python demo.py -o in command line should write the output to my default file name output.txt . 命令行中的python demo.py -o应该将输出写入我的默认文件名为output.txt

python demo.py -o demooutput.txt in command line should write the output to file demooutput.txt . 命令行中的python demo.py -o demooutput.txt应该将输出写入文件demooutput.txt

PS: I would not prefer to switch to argparse from optparse . PS:我不希望从optparse切换到argparse

You can use optparse-callbacks to achieve this. 您可以使用optparse-callbacks实现此目的。

Here is how it wiill work for your use case. 这是在您的用例中有效的方法。

parser.add_option("-o", action="callback", dest="output", callback=my_callback)

def my_callback(option, opt, value, parser):
     if len(parser.rargs) > 0:
         next_arg = parser.rargs[0]
         if not next_arg.startswith("-"):
             # Next argument is not another option
             del parser.rargs[0]
             setattr(parser.values, option.dest, next_arg)
             return
     # If not processed, set the default value
     setattr(parser.values, option.dest, "output.txt")

I don't think there is unfortunately - the only way I can think of is hacking around the problem by adding your own logic statements. 我不认为这是不幸的-我能想到的唯一方法是通过添加自己的逻辑语句来解决问题。 The following code should do the trick. 以下代码可以解决问题。

import re, sys
import optparse from OptionParser    
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
if '-f' in argv:
    a = argv.index('-f')
    if (a != len(argv)-1) and re.search('[.]txt', argv[a+1]):
        parser.add_option("-f", "--foo", dest="foo")
    else:
        parser.add_option("-f", dest="foo", action="store_true")

This doesn't answer the direct question, 'how to define an Action...', but it handles the inputs in a simple way. 这没有回答直接的问题“如何定义一个动作...”,而是以一种简单的方式处理输入。

Set '-o' to be 'store_true' . '-o'设置为'store_true' If True check the 'args' variable for a file name. 如果为True,请在'args'变量中检查文件名。

(options, args) = parser.parse_args()
if options.o:
    if args:
        dest = args[0]
    else:
        dest = 'output.txt'
else:
    dest = ''

(In argparse the equivalent would be to define a positional argument with nargs='?' .) (在argparse ,等效方法是使用nargs='?'定义位置参数。)

If these are the only arguments, you could also get by with checking for the filename without requiring the `-o' . 如果只有这些参数,则还可以通过检查文件名来实现,而无需使用`-o'

Another possibility - 'store_const', with the positional 'filename' having priority: 另一种可能性-'store_const',其中位置'filename'具有优先权:

parser = optparse.OptionParser()
parser.add_option('-o',dest='dest',action='store_const', const='output.txt', default='')
(options, args) = parser.parse_args()
if args:
    options.dest = args[0]
print options

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM