python NameError:未定义全局名称'\u file\uuu'

2024-05-16 10:20:19 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python2.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']
      )

Tags: path代码readoslibpackagessetupdescription
3条回答

你在用交互式翻译吗?你可以用

sys.argv[0]

你应该读:How do I get the path of the current executed file in Python?

我对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)

使用上述代码,您可以将应用程序添加到操作系统的路径中,您可以在任何地方执行它,而不会出现应用程序找不到其数据/配置文件的问题。

用python测试:

  • 3.3.4条
  • 2.7.13条

当您在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,它会工作,因为它采用您的文件路径。

相关问题 更多 >