[英]python passing command line argument with-in program
I have below python program takes argument from command line. 我在下面的python程序中从命令行获取参数。
import argparse
import sys
choice=['orange','apple', 'grapes', 'banna']
def select():
parser = argparse.ArgumentParser(prog='one', description='name test')
parser.add_argument(
'fname',
action="store",
type=str,
choices=choice,
help="furits name")
args = parser.parse_args(sys.argv[1:2])
print 'selected name {0}\n'.format(args.fname)
if __name__ == '__main__':
select()
this works 这有效
python s.py apple
selected name apple
How can inline argument with-in main function. 如何在主函数中内联参数。 I tried this but its not working.
我试过了,但是没有用。
change main line this. 改变主线。
if __name__ == '__main__':
sys.argv[0]='apple'
select()
getting below error. 低于错误。
usage: one [-h] {orange,apple,grapes,banna} one: error: too few arguments
How can I achieve this in argument? 如何在争论中实现这一目标?
thanks -SR 谢谢-SR
Your index is wrong sys.argv[0]
will be the path of the python script. 您的索引错误
sys.argv[0]
将是python脚本的路径。 What you want is: 您想要的是:
if __name__ == '__main__':
if len(sys.argv) == 1:
sys.argv.append("apple")
select()
But, this is a weird way of doing things. 但是,这是一种奇怪的处理方式。 After a bit more thought, this occurred to me:
经过一番思考,这发生在我身上:
choice=['orange','apple', 'grapes', 'banna']
def select():
parser = argparse.ArgumentParser(prog='one', description='name test')
parser.add_argument(
'fname',
nargs='?',
default='apple',
action="store",
type=str,
choices=choice,
help="furits name")
args = parser.parse_args(sys.argv[1:2])
print 'selected name {0}\n'.format(args.fname)
if __name__ == '__main__':
select()
Note the nargs='?'
注意
nargs='?'
and default='apple'
additions to the call to add_argument(). 和对add_argument()调用的
default='apple'
添加。 These make the parameter optional and set the default value to "apple" if no argument is supplied. 这些使参数成为可选参数,如果未提供任何参数,则将默认值设置为“ apple”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.