Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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:

/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
like image 656
yufeng.pyf Avatar asked Sep 23 '22 03:09

yufeng.pyf


1 Answers

Your thread is running past the lifetime of the module.

Your Python program exits, right after you started the thread. At that point, Python starts to clean up everything, including cleaning up the module globals. The __file__ name is one of the first things to go.

If you add a sleep at the end of the module, the __file__ name lives long enough for your thread to finish:

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; you get the same issues if you remove the if but leave other statements in between.

like image 67
Martijn Pieters Avatar answered Sep 27 '22 03:09

Martijn Pieters