我在线程__file__中的if语句中使用时报错,代码如下:
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()
Run Code Online (Sandbox Code Playgroud)
结果是:起初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
Run Code Online (Sandbox Code Playgroud)
您的线程运行时间已超过模块的生命周期。
你的 Python 程序在你启动线程后立即退出。此时,Python 开始清理所有内容,包括清理模块全局变量。名字__file__是首先要做的事情之一。
如果您在模块末尾添加 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)
Run Code Online (Sandbox Code Playgroud)
这一if声明是在转移注意力;如果删除if但在中间保留其他语句,您会遇到相同的问题。