[英]python NameError: global name '__file__' is not defined
當我在python 2.7中運行此代碼時,出現此錯誤:
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\pyutilib.subprocess-3.5.4\setup.py", line 30, in <module>
long_description = read('README.txt'),
File "C:\Python26\Lib\site-packages\pyutilib.subprocess-3.5.4\setup.py", line 19, in read
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
NameError: global name '__file__' is not defined
代碼是:
import os
from setuptools import setup
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(name="pyutilib.subprocess",
version='3.5.4',
maintainer='William E. Hart',
maintainer_email='wehart@sandia.gov',
url = 'https://software.sandia.gov/svn/public/pyutilib/pyutilib.subprocess',
license = 'BSD',
platforms = ["any"],
description = 'PyUtilib utilites for managing subprocesses.',
long_description = read('README.txt'),
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: Microsoft :: Windows',
'Operating System :: Unix',
'Programming Language :: Python',
'Programming Language :: Unix Shell',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Software Development :: Libraries :: Python Modules'],
packages=['pyutilib', 'pyutilib.subprocess', 'pyutilib.subprocess.tests'],
keywords=['utility'],
namespace_packages=['pyutilib'],
install_requires=['pyutilib.common', 'pyutilib.services']
)
當您在python交互式外殼程序中將此行os.path.join(os.path.dirname(__file__))
追加時,就會出現此錯誤。
Python Shell
沒有檢測到當前文件路徑__file__
和它關系到你的filepath
中,你加入這行
因此,您應該在file.py
寫這行os.path.join(os.path.dirname(__file__))
。 然后運行python file.py
,它可以工作,因為它需要您的文件路徑。
我在PyInstaller和Py2exe上遇到了同樣的問題,所以我遇到了來自cx-freeze的FAQ上的解決方案。
從控制台或作為應用程序使用腳本時,以下功能將為您提供“執行路徑”,而不是“實際文件路徑”:
print(os.getcwd())
print(sys.argv[0])
print(os.path.dirname(os.path.realpath('__file__')))
資源:
http://cx-freeze.readthedocs.org/en/latest/faq.html
您的舊行(最初的問題):
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
使用以下代碼段替換您的代碼行。
def find_data_file(filename):
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = os.path.dirname(sys.executable)
else:
# The application is not frozen
# Change this bit to match where you store your data files:
datadir = os.path.dirname(__file__)
return os.path.join(datadir, filename)
使用上面的代碼,您可以將應用程序添加到os的路徑中,可以在任何位置執行它,而不會出現應用程序無法找到其數據/配置文件的問題。
用python測試過:
我通過將file當作字符串來解決,即用"__file__"
(加上引號!)代替__file__
這對我來說很好:
wk_dir = os.path.dirname(os.path.realpath('__file__'))
如果您os.path.dirname(__file__)
獲取當前的工作目錄,只要您沒有在代碼中的其他地方更改工作目錄, os.getcwd()
將為您提供與os.path.dirname(__file__)
相同的功能。 os.getcwd()
也可以在交互模式下工作。
因此os.path.join(os.path.dirname(__file__))
成為os.path.join(os.getcwd())
我遇到了__file__
不能按預期工作的情況。 但是到目前為止,以下內容並沒有使我失望:
import inspect
src_file_path = inspect.getfile(lambda: None)
如下更改您的代碼! 這個對我有用。 `
os.path.dirname(os.path.abspath("__file__"))
如果您從python shell運行命令,則會得到以下信息:
>>> __file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
您需要通過將其作為參數傳遞給python
命令來直接執行文件:
$ python somefile.py
就您而言,它實際上應該是python setup.py install
您可以使用以下方法
import os
if '__file__' in vars():
wk_dir = os.path.dirname(os.path.realpath('__file__'))
else:
print('We are running the script interactively')
請注意,使用字符串'__file__'
確實是指實際變量__file__
。 您當然可以自己測試一下。
該解決方案的額外好處是,您可以部分交互地運行腳本(例如,測試/開發腳本)並可以通過命令行運行該腳本,從而具有靈活性
我有完全相同的問題,並可能使用相同的教程 。 函數定義:
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
是越野車,因為os.path.dirname(__file__)
不會返回您需要的東西。 嘗試將os.path.dirname(__file__)
替換為os.path.dirname(os.path.abspath(__file__))
:
def read(*rnames):
return open(os.path.join(os.path.dirname(os.path.abspath(__file__)), *rnames)).read()
我剛剛向安德魯發布了當前文檔中的代碼段不起作用的消息,希望它會得到糾正。
如果您通過命令行執行文件,則可以使用此hack
import traceback
def get_this_filename():
try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
filename = traceback.extract_tb(exc_traceback)[-1].filename
return filename
這在UnrealEnginePython控制台中為我工作,調用py.exec myfile.py
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.