问题描述
在命令行中,我可以将参数传递给python文件,如下所示:
In command line I am able to pass arguments to a python file as:
python script.py arg1 arg2
然后我可以按以下方式在script.py
中检索arg1
和arg2
:
I can than retrieve arg1
and arg2
within script.py
as:
import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]
但是,我想将关键字参数发送到python脚本,并将其作为字典检索:
However, I would like to send keyword arguments to a python script, and retrieve them as a dictionary:
python script.py key1=value1 key2=value2
然后我想在python中以字典形式访问关键字参数:
Then I would like to access the keyword arguments as a dictionary within python:
{'key1' : 'value1', 'key2' : 'value2'}
这可能吗?
推荐答案
我认为您正在寻找的是argparse模块 https://docs.python.org/dev/library/argparse.html .
I think what you're looking for is the argparse module https://docs.python.org/dev/library/argparse.html.
它将允许您使用命令行选项和参数解析.
It will allows you to use command line option and argument parsing.
例如假设script.py
e.g. Assume the following for script.py
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--arg1')
parser.add_argument('--arg2')
args = parser.parse_args()
print args.arg1
print args.arg2
my_dict = {'arg1': args.arg1, 'arg2': args.arg2}
print my_dict
现在,如果您尝试:
$ python script.py --arg1 3 --arg2 4
您将看到:
3
4
{'arg1': '3', 'arg2': '4'}
作为输出.我想这就是你的追求.
as output. I think this is what you were after.
但是请阅读文档,因为这是有关如何使用argparse的 非常 的示例.例如,我传入的"3"和"4"被视为str而不是整数
But read the documentation, since this is a very watered down example of how to use argparse. For instance the '3' and '4' I passed in are viewed as str's not as integers
这篇关于Python文件关键字参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!