通过命令行传递字典参数并在 python 脚本中访问它们

Passing dictionary arguments through command line and accessing them in a python script

我正在尝试将包含参数的字典传递给 python 脚本,然后在脚本中使用该字典。我将字典保存在气流的环境变量中。

例如,脚本在命令行上应 运行 作为, python test.py dict_name

dict_name 看起来像这样,

{ "path": "firstlevel/secondlevel", "name": "xyz", "key": "12345" }

而且,我需要使用上述字典的键来代替 python 脚本中的实际值,即 test.py

我尝试在 class 的初始化函数中使用 data = sys.argv[1]。但是,它给了我一个列表而不是字典。这样,就无法使用字典的功能。

def __init__(self, data = sys.argv[1]):
    print data

我正在像这样实例化对象,

f = class_name(sys.argv[1:])

我得到的输出是,

['path', ':', 'firstlevel/secondlevel', 'name', ':', 'xyz', 'key', ':', '12345']

我的 objective 是将数据作为字典获取,而不是 python 脚本中的列表,因为我只想通过键替换 python 脚本中的值。

这是用例来更清楚地解释我的观点。

fun(name = 'xyz', key = 12345)

fun(sys.argv['name'], sys.argv['key'])

回溯

Traceback (most recent call last): File "test.py", line 13, in objec_name= class_name(sys.argv[1:]) File "test.py", line 6, in init data = json.loads(sys.argv[1]) File "C:\Users\Sarvesh Pandey\AppData\Local\Programs\Python\Python38\lib\json_init_.py", line 357, in loads return _default_decoder.decode(s) File "C:\Users\Sarvesh Pandey\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end())

JSON - 或 JavaScript 对象表示是获取 Python 对象并将它们转换为类似字符串的表示形式的一种方式,适用于传递给多种语言。

python saver.py '{"names": ["J.J.", "April"], "years": [25, 29]}'

在您的 python 脚本中,执行以下操作:

import json
data=json.loads(argv[1])

这会给你一个字典,表示你想传入的数据。

然后您可以按照您的意愿申请该函数。

fun(data['name'], data['key'])

编辑: 您还需要考虑解析问题

例如

如果你 运行 print sys.argv[1] 你可能得到 '{favorited: json 模块无法解码成 json 对象。

尝试转义您的内部引号,以便将其作为 1 个参数传递,如下所示:

"{"\""favorited"\"": false, "\""contributors"\"": null}"