python NameError:未定义全局名称“__file__”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/16771894/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python NameError: global name '__file__' is not defined
提问by Kaibing Yang
When I run this code in python 2.7, I get this error:
当我在 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
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='[email protected]',
    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']
      )
回答by Eloims
Are you using the interactive interpreter? You can use
您在使用交互式解释器吗?您可以使用
sys.argv[0]
You should read: How do I get the path of the current executed file in Python?
您应该阅读:如何在 Python 中获取当前执行文件的路径?
回答by ducin
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__)):
有问题,因为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()
I've just posted Andrew that the code snippet in current docs don't work, hopefully, it'll be corrected.
我刚刚发布了安德鲁,当前文档中的代码片段不起作用,希望它会得到纠正。
回答by Burhan Khalid
You will get this if you are running the commands from the python shell:
如果你从 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 pythoncommand:
您需要直接执行文件,将其作为参数传递给python命令:
$ python somefile.py
In your case, it should really be python setup.py install
在你的情况下,它真的应该是 python setup.py install
回答by Nilesh
This error comes when you append this line os.path.join(os.path.dirname(__file__))in python interactive shell. 
当您os.path.join(os.path.dirname(__file__))在 python 交互式 shell 中附加此行时,会出现此错误。
Python Shelldoesn't detect current file path in __file__and it's related to your filepathin which you added this line
Python Shell不检测当前文件路径__file__,它与filepath您添加此行的位置有关
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.
所以你应该os.path.join(os.path.dirname(__file__))在file.py. 然后运行python file.py,它可以工作,因为它需要您的文件路径。
回答by lsheng
I solved it by treating file as a string, i.e. put "__file__"(together with the quotes!) instead of __file__
我通过将文件视为字符串来解决它,即放置"__file__"(与引号一起!)而不是__file__
This works fine for me:
这对我来说很好用:
wk_dir = os.path.dirname(os.path.realpath('__file__'))
回答by Andrew Fallgren
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.
如果您所寻找的只是获取当前工作目录,只要您没有更改代码中其他地方的工作目录,os.getcwd()就会得到相同的结果os.path.dirname(__file__)。  os.getcwd()也可以在交互模式下工作。
So
    os.path.join(os.path.dirname(__file__))becomes
    os.path.join(os.getcwd())
于是
    os.path.join(os.path.dirname(__file__))变成
    os.path.join(os.getcwd())
回答by Kwuite
I had the same problem with PyInstaller and Py2exe so I came across the resolution on the FAQ from cx-freeze.
我在 PyInstaller 和 Py2exe 上遇到了同样的问题,所以我在 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
来源: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:
用python测试:
- 3.3.4
- 2.7.13
- 3.3.4
- 2.7.13
回答by Jojo Josiane
change your codes as follows! it works for me. `
更改您的代码如下!这个对我有用。`
os.path.dirname(os.path.abspath("__file__"))
回答by zwep
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..
请注意,使用字符串'__file__'确实是指实际变量__file__。你当然可以自己测试一下..
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
此解决方案的额外好处是当您以部分交互方式运行脚本(例如测试/开发它)时的灵活性,并且可以通过命令行运行它
回答by Todd
I've run into cases where __file__doesn't work as expected. But the following hasn't failed me so far:
我遇到过__file__无法按预期工作的情况。但到目前为止,以下内容并没有让我失望:
import inspect
src_file_path = inspect.getfile(lambda: None)
This is the closest thing to a Python analog to C's __FILE__.
这是最接近 Python 模拟 C 的东西__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 的行为与__file__C 的__FILE__. C 版本将为您提供源文件的原始路径。这对于记录错误和了解哪个源文件有错误很有用。
Python's __file__only gives you the name of the currently executing file, which may not be very useful in log output.
Python__file__只为您提供当前正在执行的文件的名称,这在日志输出中可能不是很有用。

