python 名称错误 : global name '__file__' is not defined

标签 python nameerror

当我在 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 交互式 shell 中附加此行 os.path.join(os.path.dirname(__file__)) 时,会出现此错误。

Python Shell 未检测到 __file__ 中的当前文件路径,它与您在其中添加此行的 filepath 相关

所以你应该在file.py中写入这一行os.path.join(os.path.dirname(__file__))。然后运行python file.py,它可以工作,因为它需要你的文件路径。

关于python 名称错误 : global name '__file__' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53500115/

相关文章:

python - 在枚举构造函数中使用 super() 时出现 NameError

python - NumPy 中的加权标准差

python - pytest - Windows 致命异常 : code 0x8001010d

python - 单击最小化按钮时触发pyqt事件

python - "import matplotlib.pyplot as plt"时出错

python-3.x - NameError:全局名称 'PermissionError' 未定义(python 2.x)

python - 包 'see' 本身是否在 __init__.py 中?

python - 非常奇怪的 python NameError

python - 如何在我的代码上使用多处理/多线程?

python - dill.dump_session 不适用于 getpass