小编yuf*_*pyf的帖子

python'__file__'未在线程中定义

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

5
推荐指数
1
解决办法
1152
查看次数

标签 统计

python ×1

python-2.7 ×1