Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用变量名进行Python奇怪的多处理_Python_Multiprocessing - Fatal编程技术网

使用变量名进行Python奇怪的多处理

使用变量名进行Python奇怪的多处理,python,multiprocessing,Python,Multiprocessing,一个简单的例子: #!/usr/bin/env python # -*- coding: utf-8 -*- import multiprocessing class Klass(object): def __init__(self): print "Constructor ... %s" % multiprocessing.current_process().name def __del__(self): print "... Destruc

一个简单的例子:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import multiprocessing

class Klass(object):
    def __init__(self):
        print "Constructor ... %s" % multiprocessing.current_process().name

    def __del__(self):
        print "... Destructor %s" % multiprocessing.current_process().name


if __name__ == '__main__':
    kls = Klass()
\uuu del\uu
中执行当前\u进程时出错运行:

Constructor ... MainProcess
Exception AttributeError: "'NoneType' object has no attribute 'current_process'" in <bound method Klass.__del__ of <__main__.Klass object at 0x7f5c34e52090>> ignored
它得到了正确的结果:

Constructor ... MainProcess
... Destructor MainProcess
我尝试了很多变量名,有些是ok,有些是错误

为什么不同的实例名称,会导致多处理模块在代码引发的

AttributeError: "'NoneType' object has no attribute 'current_process'"
如果在删除
kls
之前删除了全局变量
multiprocessing
。 通常,对象的删除顺序是不可预测的。然而:

从版本1.5开始,Python保证在删除其他全局变量之前,从其模块中删除名称以单个下划线开头的全局变量;如果不存在对此类全局变量的其他引用,这可能有助于确保导入的模块在调用
\uu del\uu()
方法时仍然可用

因此,如果您将实例命名为
\u kls
(带有下划线),则可以确保在删除
多处理之前将调用其
\u del\u

import multiprocessing 

class Klass(object):
    def __init__(self):
        print "Constructor ... %s" % multiprocessing.current_process().name

    def __del__(self):
        print "... Destructor %s" % multiprocessing.current_process().name


if __name__ == '__main__':
    _kls = Klass()
屈服

Constructor ... MainProcess
... Destructor MainProcess

确保在删除模块之前调用
del
方法的步骤包括

  • 使用atexit
  • 使用上下文管理器
  • 将对模块的引用保存为
    Klass
    的属性
我看到了同样的结果。。。真奇怪!彼此彼此。产生同样奇怪的结果。所以我猜你在
多处理中发现了一个bug
@jornsharpe请看unutbu的answer@Sait请看unutbu的回答非常感谢!我应该更加注意python文档的警告部分。
Constructor ... MainProcess
... Destructor MainProcess