问题:python NameError:全局名称’__file__’未定义
当我在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']
)
When I run this code in python 2.7, I get this error:
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
code is:
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']
)
回答 0
当您将此行添加os.path.join(os.path.dirname(__file__))
到python交互式shell中时,会出现此错误。
Python Shell
不会检测到其中的当前文件路径,__file__
并且与filepath
您添加此行的位置有关
所以,你应该写这条线os.path.join(os.path.dirname(__file__))
在file.py
。然后运行python file.py
,它起作用,因为它需要您的文件路径。
This error comes when you append this line os.path.join(os.path.dirname(__file__))
in python interactive shell.
Python Shell
doesn’t detect current file path in __file__
and it’s related to your filepath
in which you added this line
So you should write this line os.path.join(os.path.dirname(__file__))
in file.py
. and then run python file.py
, It works because it takes your filepath.
回答 1
我在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测试:
I had the same problem with PyInstaller and Py2exe so I came across the resolution on the FAQ from cx-freeze.
When using your script from the console or as an application, the functions hereunder will deliver you the “execution path”, not the “actual file path”:
print(os.getcwd())
print(sys.argv[0])
print(os.path.dirname(os.path.realpath('__file__')))
Source:
http://cx-freeze.readthedocs.org/en/latest/faq.html
Your old line (initial question):
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
Substitute your line of code with the following snippet.
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)
With the above code you could add your application to the path of your os, you could execute it anywhere without the problem that your app is unable to find it’s data/configuration files.
Tested with python:
回答 2
如下更改代码!这个对我有用。`
os.path.dirname(os.path.abspath("__file__"))
change your codes as follows! it works for me.
`
os.path.dirname(os.path.abspath("__file__"))
回答 3
我遇到了__file__
无法正常工作的情况。但是到目前为止,以下内容并没有使我失望:
import inspect
src_file_path = inspect.getfile(lambda: None)
这是最接近C语言的Python类似物 __FILE__
。
Python的行为与__file__
C的行为大不相同__FILE__
。C版本将为您提供源文件的原始路径。这对于记录错误和了解哪个源文件存在错误很有用。
Python __file__
仅为您提供当前正在执行的文件的名称,这在日志输出中可能不是很有用。
I’ve run into cases where __file__
doesn’t work as expected. But the following hasn’t failed me so far:
import inspect
src_file_path = inspect.getfile(lambda: None)
This is the closest thing to a Python analog to C’s __FILE__
.
The behavior of Python’s __file__
is much different than C’s __FILE__
. The C version will give you the original path of the source file. This is useful in logging errors and knowing which source file has the bug.
Python’s __file__
only gives you the name of the currently executing file, which may not be very useful in log output.
回答 4
回答 5
我通过将文件视为字符串来解决它,即放在"__file__"
(加上引号!)而不是__file__
这对我来说很好:
wk_dir = os.path.dirname(os.path.realpath('__file__'))
I solved it by treating file as a string, i.e. put "__file__"
(together with the quotes!) instead of __file__
This works fine for me:
wk_dir = os.path.dirname(os.path.realpath('__file__'))
回答 6
如果你正在寻找的是让你的当前工作目录os.getcwd()
会给你同样的事情,os.path.dirname(__file__)
只要你有没有在你的代码的其他地方改变工作目录。 os.getcwd()
也可以在交互模式下使用。
所以
os.path.join(os.path.dirname(__file__))
变成
os.path.join(os.getcwd())
If all you are looking for is to get your current working directory os.getcwd()
will give you the same thing as os.path.dirname(__file__)
as long as you have not changed the working directory elsewhere in your code. os.getcwd()
also works in interactive mode.
So
os.path.join(os.path.dirname(__file__))
becomes
os.path.join(os.getcwd())
回答 7
如果您是从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
You will get this if you are running the commands from the python shell:
>>> __file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
You need to execute the file directly, by passing it in as an argument to the python
command:
$ python somefile.py
In your case, it should really be python setup.py install
回答 8
您可以使用以下方法
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__
。您当然可以自己测试一下。
该解决方案的额外好处是,您可以部分交互地运行脚本(例如,测试/开发脚本),并且可以通过命令行运行该脚本,从而具有灵活性
What you can do is to use the following
import os
if '__file__' in vars():
wk_dir = os.path.dirname(os.path.realpath('__file__'))
else:
print('We are running the script interactively')
Note here that using the string '__file__'
does indeed refer to the actual variable __file__
. You can test this out yourself of course..
The added bonus of this solution is the flexibilty when you are running a script partly interactively (e.g. to test/develop it), and can run it via the commandline
回答 9
如果您通过命令行执行文件,则可以使用此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
If you’re exec’ing a file via command line, you can use this 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
This worked for me in the UnrealEnginePython console, calling py.exec myfile.py
回答 10
我在Jupyter笔记本电脑中遇到了同样的问题。当我使用’os.path.split(os.path.realpath(file))’时,笔记本抛出了错误。
因此,我使用了“ 文件 ”。效果很好。
I had the same problem in Jupyter notebook. While I used ‘os.path.split(os.path.realpath(file))’ , the notebook was throwing an error.
I thus used ‘file‘. It worked perfectly.
回答 11
我有完全相同的问题,并可能使用相同的教程。函数定义:
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()
我刚刚发布了Andrew消息,当前文档中的代码段不起作用,希望它会得到纠正。
I’m having exacty the same problem and using probably the same tutorial. The function definition:
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
is buggy, since os.path.dirname(__file__)
will not return what you need. Try replacing os.path.dirname(__file__)
with os.path.dirname(os.path.abspath(__file__))
:
def read(*rnames):
return open(os.path.join(os.path.dirname(os.path.abspath(__file__)), *rnames)).read()
I’ve just posted Andrew that the code snippet in current docs don’t work, hopefully, it’ll be corrected.