[英]More effective way of passing several arguments to script?
My command line script takes several arguments including strings, ints, floats and lists, and it is becoming a bit tricky to do the call with all arguments: 我的命令行脚本采用了几个参数,包括字符串,整数,浮点数和列表,并且使用所有参数进行调用变得有些棘手:
python myscript.py arg1 arg2 arg3 ... argN
To avoid having to write all arguments in the command line I have created a text file with all arguments which I simply read line by line to collect arguments. 为了避免在命令行中写入所有参数,我创建了一个包含所有参数的文本文件,我只是逐行读取以收集参数。 This is working fine, but is this the best practice for doing this?
这工作正常,但这是最佳做法吗? Are there a more effective way?
有没有更有效的方法?
You can use argpase
module. 您可以使用
argpase
模块。 Refer to the following links :) 请参考以下链接:)
https://pymotw.com/2/argparse https://pymotw.com/2/argparse
Dead simple argparse example wanted: 1 argument, 3 results 想要死的简单argparse示例:1个参数,3个结果
For me I think python getopt is the way to go. 对我来说,我认为python getopt是必经之路。
#!/usr/bin/python
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print 'Input file is "', inputfile
print 'Output file is "', outputfile
if __name__ == "__main__":
main(sys.argv[1:])
Usage: 用法:
usage: test.py -i <inputfile> -o <outputfile>
It's easier to run when you have a name for the argument. 当您为参数指定名称时,运行起来会更容易。
Ref: http://www.tutorialspoint.com/python/python_command_line_arguments.htm 参考: http : //www.tutorialspoint.com/python/python_command_line_arguments.htm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.