python NameError: global name '__file__' is not defined

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

提交回复
热议问题