使用optparse接受参数的最Python的方式 [英] Most pythonic way of accepting arguments using optparse
问题描述
我目前有利用sys.argv中[1]接受在命令行的字符串Python文件。然后,该字符串执行操作,然后返回修改后的字符串命令行。
I currently have a python file that utilizes sys.argv[1] to accept a string at the command line. It then performs operations on that string and then returns the modified string to the command line.
我想实现批量模式选项中,我可以提供的字符串(每行一个,FWIW)的文件,并使其返回到命令行,这样我可以重定向输出做这样的事情。
I would like to implement a batch mode option in which I can provide a file of strings (one per line, fwiw) and have it return to the command line so that I can redirect the output doing something like
$ python script.py -someflag file.txt > modified.txt
同时仍保留现有的能力。
while still retaining the current capabilities.
我只跑2.6,所以argparse是不是一种选择。我看到无论是教程采用argparse,getopt的,或深入到过于复杂/不适用的例子。
I am only running 2.6, so argparse is not an option. The tutorials I have seen either use argparse, getopt, or delve into examples that are too complex/don't apply.
什么是检查输入,并采取适当行动的最佳方式?
What is the best way to check the input and act appropriately?
推荐答案
argparse 仍是一个选项,它只是不内置2.6。您仍然可以安装它像任何第三方包(例如,使用的easy_install argparse
)。
argparse is still an option, it's just not built into 2.6. You can still install it like any 3rd party package (for example, using easy_install argparse
).
这code的一个例子是:
An example of code for this would be:
import sys
import argparse
p = argparse.ArgumentParser(description="script.py")
p.add_argument("-s", dest="string")
p.add_argument("-f", dest="infile")
args = p.parse_args()
if args.infile == None and args.string == None:
print "Must be given either a string or a file"
sys.exit(1)
if args.infile != None and args.string != None:
print "Must be given either a string or a file, not both"
sys.exit(1)
if args.infile:
# process the input file one string at a time
if args.string:
# process the single string
这篇关于使用optparse接受参数的最Python的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!