How to know the path the script the python run?

萝らか妹 提交于 2020-01-04 01:51:06

问题


sys.arg[0] gives me the python script. For example 'python hello.py' returns hello.py for sys.arg[0]. But I need to know where the hello.py is located in full path.

How can I do that with python?


回答1:


import sys
print(sys.path[0])

From the docs:

As initialized upon program startup, the first item of this list, sys.path[0], is the directory containing the script that was used to invoke the Python interpreter.




回答2:


os.path.abspath(sys.argv[0])



回答3:


You can use __file__, a variable that contains the full path to the module from which you access it. This doesn't necessarily have to end with the ".py" extension, but can also be ".pyc" (or None).

There is also documentation available on __file__.



来源:https://stackoverflow.com/questions/3691921/how-to-know-the-path-the-script-the-python-run

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!