简体   繁体   English

python NameError:全局名称'__file__'未定义

[英]python NameError: global name '__file__' is not defined

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='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']
      )

This error comes when you append this line os.path.join(os.path.dirname(__file__)) in python interactive shell. 当您在python交互式外壳程序中将此行os.path.join(os.path.dirname(__file__))追加时,就会出现此错误。

Python Shell doesn't detect current file path in __file__ and it's related to your filepath in 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 . 因此,您应该在file.py写这行os.path.join(os.path.dirname(__file__)) and then run python file.py , It works because it takes your filepath. 然后运行python file.py ,它可以工作,因为它需要您的文件路径。

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的FAQ上的解决方案。

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. 使用上面的代码,您可以将应用程序添加到os的路径中,可以在任何位置执行它,而不会出现应用程序无法找到其数据/配置文件的问题。

Tested with python: 用python测试过:

  • 3.3.4 3.3.4
  • 2.7.13 2.7.13

I solved it by treating file as a string, ie put "__file__" (together with the quotes!) instead of __file__ 我通过将file当作字符串来解决,即用"__file__" (加上引号!)代替__file__

This works fine for me: 这对我来说很好:

wk_dir = os.path.dirname(os.path.realpath('__file__'))

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中当前已执行文件的路径?

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.path.dirname(__file__)获取当前的工作目录,只要您没有在代码中的其他地方更改工作目录, os.getcwd()将为您提供与os.path.dirname(__file__)相同的功能。 os.getcwd() also works in interactive mode. 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())

I've run into cases where __file__ doesn't work as expected. 我遇到了__file__不能按预期工作的情况。 But the following hasn't failed me so far: 但是到目前为止,以下内容并没有使我失望:

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

change your codes as follows! 如下更改您的代码! it works for me. 这个对我有用。 ` `

os.path.dirname(os.path.abspath("__file__"))

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 python command: 您需要通过将其作为参数传递给python命令来直接执行文件:

$ python somefile.py

In your case, it should really be python setup.py install 就您而言,它实际上应该是python setup.py install

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__ . 请注意,使用字符串'__file__'确实是指实际变量__file__ You can test this out yourself of course.. 您当然可以自己测试一下。

The added bonus of this solution is the flexibilty when you are running a script partly interactively (eg to test/develop it), and can run it via the commandline 该解决方案的额外好处是,您可以部分交互地运行脚本(例如,测试/开发脚本)并可以通过命令行运行该脚本,从而具有灵活性

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. 是越野车,因为os.path.dirname(__file__)不会返回您需要的东西。 Try replacing os.path.dirname(__file__) with os.path.dirname(os.path.abspath(__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. 我刚刚向安德鲁发布了当前文档中的代码段不起作用的消息,希望它会得到纠正。

If you're exec'ing a file via command line, you can use this hack 如果您通过命令行执行文件,则可以使用此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

This worked for me in the UnrealEnginePython console, calling py.exec myfile.py 这在UnrealEnginePython控制台中为我工作,调用py.exec myfile.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM