简体   繁体   中英

How do I get the current path of the file executing the current thread?

In python, I can do this to get the current file's path:

os.path.dirname(os.path.abspath(__file__))

But if I run this on a thread say:

def do_stuff():
   class RunThread(threading.Thread):
       def run(self):
           print os.path.dirname(os.path.abspath(__file__))
   a = RunThread()
   a.start()

I get this error:

Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
    self.run()
  File "readrss.py", line 137, in run
    print os.path.dirname(os.path.abspath(__file__))
NameError: global name '__file__' is not defined
import inspect
print(inspect.stack()[0][1])

inspect

I apologise for my previous answer. I was half asleep and replied stupidly. Every time I've done what you're trying to do, I have used it in the inverse order. Eg os.path.abspath(os.path.dirname(__file__))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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