python NameError: global name '__file__' is not defined

前端 未结 12 827
误落风尘
误落风尘 2020-12-02 08:08

When I run this code in python 2.7, I get this error:

Traceback (most recent call last):
File \"C:\\Python26\\Lib\\site-packages\\pyutilib.subprocess-3.5.4\\         


        
相关标签:
12条回答
  • 2020-12-02 08:22

    This error comes when you append this line os.path.join(os.path.dirname(__file__)) in python interactive shell.

    Python Shell doesn't detect current file path in __file__ and it's related to your filepath in which you added this line

    So you should write this line os.path.join(os.path.dirname(__file__)) in file.py. and then run python file.py, It works because it takes your filepath.

    0 讨论(0)
  • 2020-12-02 08:23

    I had the same problem in Jupyter notebook. While I used 'os.path.split(os.path.realpath(file))' , the notebook was throwing an error.

    I thus used 'file'. It worked perfectly.

    0 讨论(0)
  • 2020-12-02 08:28

    I've run into cases where __file__ doesn't work as expected. But the following hasn't failed me so far:

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

    This is the closest thing to a Python analog to C's __FILE__.

    The behavior of Python's __file__ is much different than C's __FILE__. The C version will give you the original path of the source file. This is useful in logging errors and knowing which source file has the bug.

    Python's __file__ only gives you the name of the currently executing file, which may not be very useful in log output.

    0 讨论(0)
  • 2020-12-02 08:28

    You will get this if you are running the commands from the 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 somefile.py
    

    In your case, it should really be python setup.py install

    0 讨论(0)
  • 2020-12-02 08:34

    If you're exec'ing a file via command line, you can use this 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

    0 讨论(0)
  • 2020-12-02 08:36

    I had the same problem with PyInstaller and Py2exe so I came across the resolution on the FAQ from cx-freeze.

    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

    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.

    Tested with python:

    • 3.3.4
    • 2.7.13
    0 讨论(0)
提交回复
热议问题