Python:optparse 的 ACTION 属性可以像 STORE 和 STORE_TRUE 一样起作用吗? [英] Python: Can optparse have the ACTION attribute to act both like STORE and STORE_TRUE?

查看:30
本文介绍了Python:optparse 的 ACTION 属性可以像 STORE 和 STORE_TRUE 一样起作用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 optparse 来获取命令行输入.

I am using optparse to get command line input.

假设我正在运行一个脚本 demo.py 并且它创建了一些输出.但是除非我指定命令行输入,否则输出不会写入文件.

Lets say that I am running a script demo.py and it creates some output. 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 应该运行脚本,但不要将输出写入任何地方.

python demo.py in command line should run the script, but not write the output anywhere.

python demo.py -o 应该将输出写入我的默认文件名 output.txt.

python demo.py -o in command line should write the output to my default file name output.txt.

python demo.py -o demooutput.txt 在命令行中应该将输出写入文件 demooutput.txt.

python demo.py -o demooutput.txt in command line should write the output to file demooutput.txt.

PS:我不想从 optparse 切换到 argparse.

PS: I would not prefer to switch to argparse from optparse.

推荐答案

您可以使用 optparse-callbacks 来实现这一点.

You can use optparse-callbacks to achieve this.

以下是它如何适用于您的用例.

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")

这篇关于Python:optparse 的 ACTION 属性可以像 STORE 和 STORE_TRUE 一样起作用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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