从 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:40:43  来源:igfitidea点击:

Take string argument from Python command line

pythonarguments

提问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

回答by Junuxx

Check sys.argv. It gives a list with the name of the script and any command line arguments.

检查sys.argv。它给出了一个包含脚本名称和任何命令行参数的列表。

Example script:

示例脚本:

import sys
print sys.argv

Calling it:

调用它:

> python script.py foobar baz
['script.py', 'foobar', 'baz']

回答by Damian Schenkelman

If you are looking for the first parameter sys.argv[1]does the trick. More info here.

如果您正在寻找第一个参数sys.argv[1]就可以了。更多信息在这里