简体   繁体   English

python'__ file__'未在线程中定义

[英]python '__file__' is not defined in thread

I got an error when I use __file__ in a if statement in a thread, the code is as follows: 我在一个线程的if语句中使用__file__时出错,代码如下:

import os
from threading import Thread

def cur_dir():
    current_dir = os.path.dirname(os.path.abspath(__file__))
    print current_dir
    if "hello":
        print "in if"
        current_dir = os.path.dirname(os.path.abspath(__file__))
        print current_dir


t = Thread(target=cur_dir)
t.start()

the result is: at first current_dir can always be printed, but the second most time can't: 结果是:首先可以打印current_dir ,但第二次最多时间不能:

/private/tmp
in if
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "test.py", line 9, in cur_dir
    current_dir = os.path.dirname(os.path.abspath(__file__))
NameError: global name '__file__' is not defined

Your thread is running past the lifetime of the module . 您的线程正在运行模块的生命周期

Your Python program exits, right after you started the thread. 启动线程后立即退出Python程序。 At that point, Python starts to clean up everything, including cleaning up the module globals. 那时,Python开始清理所有内容,包括清理模块全局变量。 The __file__ name is one of the first things to go. __file__名称是首先要做的事情之一。

If you add a sleep at the end of the module, the __file__ name lives long enough for your thread to finish: 如果在模块末尾添加一个sleep,则__file__名称的长度足以让您的线程完成:

import os
import time
from threading import Thread

def cur_dir():
    current_dir = os.path.dirname(os.path.abspath(__file__))
    print current_dir
    if "hello":
        print "in if"
        current_dir = os.path.dirname(os.path.abspath(__file__))
        print current_dir


t = Thread(target=cur_dir)
t.start()
time.sleep(1)

The if statement is a red herring; if语句是一个红色的鲱鱼; you get the same issues if you remove the if but leave other statements in between. 如果删除if但在其间留下其他语句, if出现相同的问题。

While Martijn Pieters diagnosis is good, you should not depend on timing to ensure that needed variables are available (ie don't depend on sleep lasting long enough) 虽然Martijn Pieters诊断良好,但您不应该依赖时间来确保所需的变量可用(即不要长时间依赖睡眠)

Instead, use Thread.join to make main thread wait for its children: 相反,使用Thread.join使主线程等待其子代:

t = Thread(target=cur_dir)
t.start()
t.join()

Or, when starting multiple threads: 或者,当启动多个线程时:

threads = []

for i in range(5):
    t = Thread(target=cur_dir)
    t.start()
    threads.append(t)

for t in threads:
    t.join()

Note dual loops, as you want to start all the threads before locking the parent, waiting for each of its children to finish. 注意双循环,因为你想在锁定父节点之前启动所有线程,等待它的每个子节点完成。

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

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