我正在尝试从终端获取多个文件作为输入。输入数字可能从至少1到很多不等。这是我的程序的输入
F3.py -e <Energy cutoff> -i <inputfiles>
我希望参数-i从1到multip.e.g。
取任意数量的值F3.py -e <Energy cutoff> -i file1 file2
F3.py -e <Energy cutoff> -i *.pdb
现在它只需要第一个文件然后停止。 这就是我到目前为止所做的:
def main(argv):
try:
opts,args=getopt.getopt(argv,"he:i:")
for opt,arg in opts:
if opt=="-h":
print 'F3.py -e <Energy cutoff> -i <inputfiles>'
sys.exit()
elif opt == "-e":
E_Cut=float(arg)
print 'minimum energy=',E_Cut
elif opt == "-i":
files.append(arg)
print files
funtction(files)
except getopt.GetoptError:
print 'F3.py -e <Energy cutoff> -i <inputfiles>'
sys.exit(2)
任何帮助将不胜感激。感谢
答案 0 :(得分:1)
尝试使用@larsks建议,下一个代码段适用于您的用例:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', help='Input values', nargs='+', required=True)
args = parser.parse_args()
print args
kwargs解释:
nargs
允许您将值解析为列表,因此您可以使用以下内容进行迭代:for i in args.input
。required
强制使用此参数,因此您必须添加至少一个元素通过使用argparse模块,您还可以使用-h选项来描述参数。所以尝试使用:
$ python P3.py -h
usage: a.py [-h] -i INPUT [INPUT ...]
optional arguments:
-h, --help show this help message and exit
-i INPUT [INPUT ...], --input INPUT [INPUT ...]
Input values
$ python P3.py -i file1 file2 filen
Namespace(input=['file1', 'file2', 'filen'])
答案 1 :(得分:1)
如果您坚持使用getopt
,则必须将多个参数与除,
之类的空格之外的分隔符合并,然后相应地修改您的代码
import getopt
import sys
try:
opts,args=getopt.getopt(sys.argv[1:],"he:i:")
for opt,arg in opts:
if opt=="-h":
print 'F3.py -e <Energy cutoff> -i <inputfiles>'
sys.exit()
elif opt == "-e":
E_Cut=float(arg)
print 'minimum energy=',E_Cut
elif opt == "-i":
files = arg.split(",")
print files
#funtction(files)
except getopt.GetoptError:
print 'F3.py -e <Energy cutoff> -i <inputfiles>'
sys.exit(2)
当你运行它时,你将得到输出
>main.py -e 20 -i file1,file2
minimum energy= 20.0
['file1', 'file2']
注意强> 我已经对你的函数调用进行了评论并删除了从main函数中解包你的代码,你可以在代码中重做这些东西,它不会改变你的结果。