gpt4 book ai didi

python '__file__' 未在线程中定义

转载 作者:行者123 更新时间:2023-11-28 17:29:05 26 4
gpt4 key购买 nike

在线程中的if语句中使用__file__时出现错误,代码如下:

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()

结果是:一开始总是可以打印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

最佳答案

您的线程运行超过了模块的生命周期

您的 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)

if 语句是一个转移注意力的问题;如果您删除 if 但在其间保留其他语句,您会遇到同样的问题。

关于python '__file__' 未在线程中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35915852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com