132

当我在 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']
      )
4

11 回答 11

166

当您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,它可以工作,因为它需要你的文件路径。

于 2013-12-11T04:27:35.060 回答
31

我在 PyInstaller 和 Py2exe 上遇到了同样的问题,所以我在 cx-freeze 的常见问题解答中遇到了解决方案。

从控制台或作为应用程序使用您的脚本时,下面的函数将为您提供“执行路径”,而不是“实际文件路径”:

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
于 2017-01-09T11:18:43.140 回答
21

我遇到了__file__无法按预期工作的情况。但到目前为止,以下内容并没有让我失望:

import inspect
src_file_path = inspect.getfile(lambda: None)

这是最接近 C 语言的 Python 类比的东西__FILE__

Python 的行为与__file__C 的行为有很大不同__FILE__。C 版本将为您提供源文件的原始路径。这对于记录错误和了解哪个源文件有错误很有用。

Python__file__只为您提供当前正在执行的文件的名称,这在日志输出中可能不是很有用。

于 2018-11-14T05:51:45.197 回答
19

更改您的代码如下!这个对我有用。`

os.path.dirname(os.path.abspath("__file__"))
于 2018-07-01T08:36:36.353 回答
10

如果您正在寻找的只是获取当前工作目录,那么只要您没有在代码中的其他地方更改工作目录,您 os.getcwd()就会得到同样的结果。也可以在交互模式下工作。os.path.dirname(__file__)os.getcwd()

所以 os.path.join(os.path.dirname(__file__)) 变成 os.path.join(os.getcwd())

于 2015-01-28T23:07:57.803 回答
9

你在使用交互式解释器吗?您可以使用

sys.argv[0]

您应该阅读:如何在 Python 中获取当前执行文件的路径?

于 2013-05-27T11:20:44.923 回答
6

如果你从 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

于 2013-11-24T11:14:33.957 回答
3

如果您正在通过命令行执行文件,则可以使用此 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

于 2018-12-30T19:30:05.820 回答
1

如果您使用的是 jupyter 笔记本,例如:

MODEL_NAME = os.path.basename(文件)[:-3]

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-10-f391bbbab00d> in <module>
----> 1 MODEL_NAME = os.path.basename(__file__)[:-3]

NameError: name '__file__' is not defined

你应该放置一个'!'前面这样

!MODEL_NAME = os.path.basename(__file__)[:-3]

/bin/bash: -c: line 0: syntax error near unexpected token `('
/bin/bash: -c: line 0: `MODEL_NAME = os.path.basename(__file__)[:-3]'

完毕.....

于 2020-12-21T21:50:56.107 回答
0

我遇到了完全相同的问题,并且可能使用了相同的教程。函数定义:

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 发布了当前文档中的代码片段不起作用,希望它会得到纠正。

于 2013-11-24T11:08:24.097 回答
0

我认为您可以执行此操作以获取本地文件路径

if not os.path.isdir(f_dir):
    os.mkdirs(f_dir)

try:
    approot = os.path.dirname(os.path.abspath(__file__))
except NameError:
    approot = os.path.dirname(os.path.abspath(sys.argv[1]))
    my_dir= os.path.join(approot, 'f_dir')
于 2021-02-21T16:10:18.910 回答