python NameError: global name '__file__' is not defined

前端 未结 12 826
误落风尘
误落风尘 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:11

    I solved it by treating file as a string, i.e. put "__file__" (together with the quotes!) instead of __file__

    This works fine for me:

    wk_dir = os.path.dirname(os.path.realpath('__file__'))
    
    0 讨论(0)
  • 2020-12-02 08:12

    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.getcwd() also works in interactive mode.

    So os.path.join(os.path.dirname(__file__)) becomes os.path.join(os.getcwd())

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

    change your codes as follows! it works for me. `

    os.path.dirname(os.path.abspath("__file__"))
    
    0 讨论(0)
  • 2020-12-02 08:14

    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__. 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 (e.g. to test/develop it), and can run it via the commandline

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

    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?

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

    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. Try replacing os.path.dirname(__file__) with 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.

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