用eval开始一个过程

时间:2015-02-01 18:04:05

标签: python process eval

   **exe.py**
    def createProcess(f):
        try:
            from multiprocessing import Process
            newProcess = Process(target=f)
            newProcess.start()
            newProcess.join()
        except:
            print "Error creating process"

    def lala():
        print "success creating process"

    print "tying to make a process"
    from multiprocessing import Process
    newProcess = Process(target=lala)
    newProcess.start()

    **main.py**
    if __name__ == '__main__':
        f = open("exe.py", "r")
        b = f.read()
        f.close()
        o = compile(b, "exe.py", "exec")
        eval(o)

我收到以下错误

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Program Files\Opsware\agent\lcpython15\lib\multiprocessing\forking.p
    ", line 374, in main
        self = load(from_parent)
      File "C:\Program Files\Opsware\agent\lcpython15\lib\pickle.py", line 1378, in
    load
        return Unpickler(file).load()
      File "C:\Program Files\Opsware\agent\lcpython15\lib\pickle.py", line 858, in
    oad
        dispatch[key](self)
      File "C:\Program Files\Opsware\agent\lcpython15\lib\pickle.py", line 1090, in
    load_global
        klass = self.find_class(module, name)
      File "C:\Program Files\Opsware\agent\lcpython15\lib\pickle.py", line 1126, in
    find_class
        klass = getattr(mod, name)
    AttributeError: 'module' object has no attribute 'lala'

稍后编辑

我将exe.py更改为

    def lala2():
        f = open("C:\\work\\asdfas", "w")
        f.write("dsdfg\r\n")
        f.close()
        print "success creating process"

    if __name__ == '__main__':
        print "tying to make a process"
        from multiprocessing import Process, freeze_support 
        freeze_support()
        import pickle
        l = pickle.dumps(lala2)
        pickle.loads(l)()
        newProcess = Process(target=pickle.loads(l))
        newProcess.daemon = True
        newProcess.start()
        if newProcess.is_alive() == True:
            print "alive"
        else:
            print "not alive"
        import time
        time.sleep(12)

这应该可以导入它,并且由于pickle测试它显示我的方法是可选择的。关于它为何如此行事的任何建议?

1 个答案:

答案 0 :(得分:2)

你在Windows上。不幸的是,在Windows上,不可能将动态代码对象用作multiprocessing的目标,因为多处理的Windows实现必须能够导入主模块(技术原因是因为Windows缺少本机{{ 1}}等价物)。有关适用限制的详细信息,请参阅multiprocessing programming guidelines for Windows

解决方案是将代码写入文件,然后fork()将其写入服务器。