问题
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