Python命令行脚本.两种使用场景.如何实现参数解析?

clu*_*ter 1 python parsing args command-line-arguments argparse

我有一个python命令行脚本,可以以两种不同的方式使用.

第一种情况是这样的:

script.py -max MAX -min MIN -delta DELTA
Run Code Online (Sandbox Code Playgroud)

where -max-min是必需的参数,-delta是可选的.

第二种情况是:

script.py some_file.txt -f
Run Code Online (Sandbox Code Playgroud)

其中some_file.txt是必需的位置参数,-f是可选的.

我如何使用任何Python命令行参数解析器(argparse,optparse,getopt等)实现它?

更新:脚本只做一件事 - 刮擦网站.但它的运作时间很长.在第一种情况下,我们运行新的scrape会话,而在第二次加载之前保存的会话并继续报废.

Gan*_*ndi 6

我这样做:

parser = OptionParser()
parser.add_option("-max", dest="max")
parser.add_option("-min", dest="min")
parser.add_option("-delta", dest="delta")
parser.add_option("-f", dest="f_thing", action="store_true")

(options,args) = parser.parse_args()

if not args:
    if not options.max or not options.min:
        parser.error("Please provide a max and min value.")
    else:
        yourfunction(options, args) # without some_file.txt name
else:
        yourfunctions(options, args) # pass the some_file.txt name
Run Code Online (Sandbox Code Playgroud)

我不确定,如果这是你想要的100%,但我认为这个问题有点过于接近.那会让你有所了解,你的目标是如何实现的.