我在线程__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)