shell管道列表到另一个python文件的字典

时间:2017-12-10 22:49:37

标签: python json dictionary

我想将一个字典列表管道到另一个python文件 如何输出该词典列表并将其作为其他文件中的词典列表读取

这是清单

     [{96: {'p_user_id': 97,
       'product-id': 459715,
       'user_id': 97,
       'user_location': '980 belle plaine, dallas, texas, united states, '
                        '75448'},
  97: {'p_user_id': 98,
       'product-id': 350361,
       'user_id': 98,
       'user_location': '6225 midway airport, nashville, tennessee, united '
                        'states, 37552 '},
  98: {'p_user_id': 99,
       'product-id': 183572,
       'user_id': 99,
       'user_location': '5044 neva, sacramento, california, united states, '
                        '95022'},
  99: {'p_user_id': 100,
       'product-id': 563781,
       'user_id': 100,
       'user_location': '7531 9th, little rock, arkansas, united states, '
                        '72158 '}}]

1 个答案:

答案 0 :(得分:0)

如果您发布了代码而不是JSON,那将会有所帮助,但这是一种简单的方法:

# parent.py
import json
import subprocess

transfer_dict = {"name": "Bob", "msg": "Hello"}  # dict to transfer

# start our sub-process calling the child.py
proc = subprocess.Popen(["python", "child.py"], stdout=subprocess.PIPE,
                        stdin=subprocess.PIPE, universal_newlines=True)
# serialize to JSON, send to the subprocess and wait for a response
stdout, _ = proc.communicate(json.dumps(transfer_dict))

print("child.py responded with: " + stdout)  # finally, print out the response

然后编写子进程:

# child.py
import json

data = input()  # awaiting input from parent.py, use raw_input() on Python 2.x

transfer_dict = json.loads(data)  # deserialize back to dict

# print out what we've received
print("Hey {}, {} to you too!".format(transfer_dict["name"], transfer_dict["msg"]))

我正在使用JSON,因为它不是一个麻烦而不是泡菜,你已经在你的问题中标记了它。运行它将产生:

child.py responded with: Hey Bob, Hello to you too!

证明transfer_dict字典已成功传输。