Python 使用 argparse 打印命令行参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34992524/
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-19 15:51:05  来源:igfitidea点击:

Print command line arguments with argparse?

pythonpython-2.7argparse

提问by becko

I am using argparseto parse command line arguments.

我正在使用argparse解析命令行参数。

To aid debugging, I would like to printa line with the arguments which with the Python script was called. Is there a simple way to do this within argparse?

为了帮助调试,我想添加print一行,其中包含调用 Python 脚本的参数。有没有一种简单的方法可以做到这一点argparse

采纳答案by poke

ArgumentParser.parse_argsby default takes the arguments simply from sys.argv. So if you don't change that behavior (by passing in something else to parse_args), you can simply print sys.argvto get all arguments passed to the Python script:

ArgumentParser.parse_args默认情况下,仅从sys.argv. 因此,如果您不更改该行为(通过将其他内容传递给parse_args),您可以简单地打印sys.argv以获取传递给 Python 脚本的所有参数:

import sys
print(sys.argv)

Alternatively, you could also just print the namespace that parse_argsreturns; that way you get all values in the way the argument parser interpreted them:

或者,您也可以只打印parse_args返回的命名空间;这样你就可以按照参数解析器解释它们的方式获得所有值:

args = parser.parse_args()
print(args)

回答by Noam Manos

If running argparse within another python script(e.g. inside unittest), then printing sys.argvwill only print the arguments of the main script, e.g.:

如果在另一个 python 脚本中运行argparse(例如在unittest 中),那么打印sys.argv只会打印主脚本的参数,例如:

['C:\eclipse\plugins\org.python.pydev_5.9.2.201708151115\pysrc\runfiles.py', 'C:\eclipse_workspace\test_file_search.py', '--port', '58454', '--verbosity', '0']

['C:\eclipse\plugins\org.python.pydev_5.9.2.201708151115\pysrc\runfiles.py', 'C:\eclipse_workspace\test_file_search.py​​', '--port', '58454', '--详细', '0']

In this case you should use varsto iterate over argparse args:

在这种情况下,您应该使用vars来迭代 argparse args:

parser = argparse.ArgumentParser(...
...
args = parser.parse_args()
for arg in vars(args):
    print arg, getattr(args, arg)

Thanks to: https://stackoverflow.com/a/27181165/658497

感谢:https: //stackoverflow.com/a/27181165/658497