python NameError: global name '__file__' is not defined

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

提交回复
热议问题