python NameError : 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 NameError : global name '__file__' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16771894/

相关文章:

ruby - 未初始化的常量记录器 (NameError)

python - 磁盘空间效率最高的内存映射字典,用于 2000 万个键值对,速度不是太关心的问题

python - 将求值表达式传递给 Python 中的递归时出现问题

python - 主题分布 : How do we see which document belong to which topic after doing LDA in python

Python:从具有字符限制的列表中生成所有可能的序列组合

python - numpy 1.9.2+MKL 与 py2exe 打包时出现 OMP 警告

python - iPython 调试器引发 `NameError: name ... is not defined`

python - openAi-gym 名称错误

Python 名称错误 : name 'file_name' is not defined

python - 为什么我会收到 NameError : name 'train_test_split' is not defined?