简体   繁体   English

如何通过subprocess.Popen接收pickle

[英]How to receive pickle via subprocess.Popen

getPickle.py getPickle.py

import pickle
import subprocess

cmd = ['rsh', 'host1', 'sendPickle.py']
p  = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
results = pickle.load(stdout)
print results

sendPickle.py sendPickle.py

import pickle
import sys

to_return = {'a':1, 'b': 2}
pickle.dump(to_return, sys.stdout)

OUTPUT: OUTPUT:

File "getPickle" line 10, in <module>
    results = pickle.load(stdout)
AttributeError: 'str' object has no attribute 'readline'

What can I do to get pickle back from stdout? 我该怎么做才能从stdout回来泡菜?

Thank you 谢谢

Use pickle.loads to load the pickle from a string. 使用pickle.loads从字符串加载pickle。 pickle.load is for loading from a stream. pickle.load用于从流中加载。

Two unrelated remarks: 两个不相关的评论:

  • if you are using Python 2, you probably want to import cPickle as pickle because the C version is many time faster and just as powerful. 如果您使用的是Python 2,您可能希望import cPickle as pickle因为C版本的速度要快很多,同样强大。

  • unless you specifically want to support older Python versions, it is a good idea to use protocol=-1 on the dump side in order specify the latest Pickle protocol, which is more efficient than the default lowest/oldest version. 除非您特别想要支持旧的Python版本,否则最好在转储端使用protocol=-1 ,以便指定最新的Pickle协议,该协议比默认的最低/最旧版本更有效。

@user4815162342 gives the correct answer. @ user4815162342给出了正确答案。 To make it crystal clear, here's example code showing how to retrieve the pickled object. 为了清楚起见,这里的示例代码显示了如何检索pickle对象。

Note that it's a bit of an unusual case to pair dump and loads , but that's what needs to be done as p.communicate returns the string from stdout. 请注意,配对dumploads是一种不寻常的情况,但这是需要做的事情,因为p.communicate从stdout返回字符串。

>>> import pickle
>>> import subprocess as sp
>>> cmd = ['python', 'sendPickle.py']
>>> p = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE)
>>> stdout, stderr = p.communicate()
>>> stdout
"(dp0\nS'a'\np1\nI1\nsS'b'\np2\nI2\ns."
>>> results = pickle.loads(stdout)
>>> results
{'a': 1, 'b': 2}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM