import multiprocessing
import time
import pycurl
class Bot(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
self.c = pycurl.Curl()
def run(self):
pass
if __name__ == '__main__':
Bot().start()
此代码在Ubuntu 13.04 x64上运行良好,但在Windows 7 x64 / Server 2008 x64上运行失败。我使用pyCurl 7.19.0和Python 2.7。 错误是:
Z:\bot>python test.py
Traceback (most recent call last):
File "test.py", line 74, in <module>
Bot().start()
File "C:\Python27\lib\multiprocessing\process.py", line 104, in start
self._popen = Popen(self)
File "C:\Python27\lib\multiprocessing\forking.py", line 244, in __init__
dump(process_obj, to_child, HIGHEST_PROTOCOL)
File "C:\Python27\lib\multiprocessing\forking.py", line 167, in dump
ForkingPickler(file, protocol).dump(obj)
File "C:\Python27\lib\pickle.py", line 224, in dump
self.save(obj)
File "C:\Python27\lib\pickle.py", line 331, in save
self.save_reduce(obj=obj, *rv)
File "C:\Python27\lib\pickle.py", line 419, in save_reduce
save(state)
File "C:\Python27\lib\pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "C:\Python27\lib\pickle.py", line 649, in save_dict
self._batch_setitems(obj.iteritems())
File "C:\Python27\lib\pickle.py", line 681, in _batch_setitems
save(v)
File "C:\Python27\lib\pickle.py", line 313, in save
(t.__name__, obj))
pickle.PicklingError: Can't pickle 'Curl' object: <pycurl.Curl object at 0x00000
00002360478>
Z:\bot>Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Python27\lib\multiprocessing\forking.py", line 347, in main
self = load(from_parent)
File "C:\Python27\lib\pickle.py", line 1378, in load
return Unpickler(file).load()
File "C:\Python27\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python27\lib\pickle.py", line 880, in load_eof
raise EOFError
EOFError
为什么会这样?
答案 0 :(得分:1)
在posix系统上,multiprocessing
使用fork()
系统调用来克服正在运行的进程及其所有状态(包括复杂类的实例,例如pycurl.Curl
)。
Windows没有fork()
或类似的东西,因此multiprocessing
会为每个子进程启动一个新的python解释器,并使用一个特殊的存根函数来侦听父进程并重新创建状态所以它看起来很像fork()
被使用过。 multiprocessing
使用的关键技术是,它在父进程中使用时重新创建子进程中的每个对象。这可以通过将对象转换为字节码表示(使用pickle
模块),通过管道将它们发送给子节点,然后将它们转换回python对象。
对于大多数类型的python对象,这非常有效,并且对您来说是透明的。有许多显而易见的事情,这是不可能的;打开文件不能以这种方式传递;非python库对象的状态也是如此,它们对pickle
系统一无所知。不幸的是,pycurl
是这两件事的一部分。