如 Most pythonic way of accepting arguments using optparse 的已接受答案中所述,我有一个程序,该程序具有对字符串执行操作的功能。该程序使用 argparse 检查字符串是按原样提供还是在文件中提供,并根据需要处理输入以将其传递给函数。
现在我想用我的功能的更高级版本扩展程序,但仍保留基本版本以供比较,有点像 Use argparse to run 1 of 2 functions in my script .我认为我的情况不同之处在于,无论调用的是什么函数,我都希望选择也传递我现有的输入标志。
只是向解析器添加一个新参数并将我以前的代码嵌套在检查该标志的 if/else 中是行不通的:它提示参数数量错误。我知道子命令,但我对 argparse 还是很陌生,看起来这对我想要的东西来说太过分了——但也许不是。
tl;dr:我需要选择两个函数之一和两个输入类型之一;两种输入类型都适用于两种功能。感谢您的帮助!
编辑添加代码:
p = argparse.ArgumentParser(description="program.py")
p.add_argument("-e", dest='extended') #The new flag causing the trouble
p.add_argument("-s", dest="string")
p.add_argument("-f", dest="infile")
args = p.parse_args()
if args.extended:
if args.infile:
with open(args.infile,'r') as f:
for line in enumerate(f.readlines()):
print 'Input: ', line[1],
output = funcExtended(line[1]) #new and improved function
print 'Extended output: ', output
elif args.string:
output = funcExtended(args.string)
print output
else: #my future default option to grab strings from a database
print 'This will soon work: extended'
else: #I fully realize that I shouldn't have to essentially copy and paste here
if args.infile:
with open(args.infile,'r') as f:
for line in enumerate(f.readlines()):
print 'Input: ', line[1],
output = funcBasic(line[1]) #old and tired function
print 'Basic output: ', output
elif args.string:
output = funcBasic(args.string)
print output
else: #my future default option to grab strings from a database
print 'This will soon work: basic'
这是一个命令行工具。发行
$ python program.py -s 'string'
像以前一样返回格式正确的字符串。但是发行
$ python program.py -s 'string' -e
返回
program.py: error: argument -e: expected one argument
哇哦。再次感谢任何可以提供帮助的人!
最佳答案
如果您将extended
参数更改为 bool 标志
p.add_argument("-e", dest='extended', action="store_true")
它将不再期待争论。然后您可以使用
调用您的脚本$ python program.py -e -s 'string'
最后,作为奖励,这里有一些想法可以减少您的代码冗余:
import argparse
def funcExtended(line):
return " ".join(line)
def funcBasic(line):
return line.upper()
p = argparse.ArgumentParser(description="program.py")
p.add_argument("-e", "--extended", dest="func", action="store_const", const=funcExtended, default=funcBasic)
p.add_argument("-s", "--string")
p.add_argument("-f", "--infile")
args = p.parse_args()
def readlines(args):
if args.infile:
with open(args.infile,'r') as f:
for line in f:
yield line.rstrip("\n")
elif args.string:
yield args.string
else: #my future default option to grab strings from a database
print 'This will soon work: extended'
for line in readlines(args):
print 'Input: ', line
output = args.func(line)
print "Output: ", output
关于python - 使用 argparse 选择函数和供应选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12419249/