How do you properly determine the current script directory in Python?

后端 未结 12 1822
情深已故
情深已故 2020-11-22 02:30

I would like to see what is the best way to determine the current script directory in Python.

I discovered that, due to the many ways of calling Python code, it is ha

12条回答
  •  滥情空心
    2020-11-22 02:58

    Hopefully this helps:- If you run a script/module from anywhere you'll be able to access the __file__ variable which is a module variable representing the location of the script.

    On the other hand, if you're using the interpreter you don't have access to that variable, where you'll get a name NameError and os.getcwd() will give you the incorrect directory if you're running the file from somewhere else.

    This solution should give you what you're looking for in all cases:

    from inspect import getsourcefile
    from os.path import abspath
    abspath(getsourcefile(lambda:0))
    

    I haven't thoroughly tested it but it solved my problem.

提交回复
热议问题