从 Python 命令行获取字符串参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12714461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Take string argument from Python command line
提问by Kreuzade
I need to take an optional argument when running my Python script:
运行 Python 脚本时,我需要采用可选参数:
python3 myprogram.py afile.json
or
或者
python3 myprogram.py
This is what I've been trying:
这是我一直在尝试的:
filename = 0
parser = argparse.ArgumentParser(description='Create Configuration')
parser.add_argument('filename', type=str,
help='optional filename')
if filename is not 0:
json_data = open(filename).read()
else:
json_data = open('defaultFile.json').read()
I was hoping to have the filename stored in my variable called "filename" if it was provided. Obviously this isn't working. Any advice?
如果提供了文件名,我希望将文件名存储在名为“filename”的变量中。显然这是行不通的。有什么建议吗?
采纳答案by dm03514
Please read the tutorial carefully. http://docs.python.org/howto/argparse.html
请仔细阅读教程。http://docs.python.org/howto/argparse.html
i believe you need to actually parse the arguments:
我相信你需要真正解析参数:
parser = argparse.ArgumentParser()
args = parser.parse_args()
then filename will be come available args.filename
然后文件名将可用 args.filename

