如何获取python程序的完整路径,包括程序中的文件名? [英] How to get full path to python program including filename within the program?
问题描述
我有一个 python 程序,我想从程序中获取程序的路径,但包括文件名本身.我的文件名为 PyWrapper.py.现在我正在这样做:
I have a python program, and I want to get the path to the program from within the program, but INCLUDING the file name itself. The name of my file is PyWrapper.py. Right now I'm doing this:
import sys,os
pathname = os.path.dirname(sys.argv[0])
fullpath = os.path.abspath(pathname)
print fullpath
输出为:
/home/mrpickles/Desktop/HANSTUFF/securesdk/src/
这是保存我的文件的目录的路径,但我希望它输出:
This is the path to the directory in which my file is saved, but I would like it to output:
/home/mrpickles/Desktop/HANSTUFF/securesk/src/PyWrapper.py/
哪个是路径,包括文件名本身.这可能吗?谢谢.
Which is the path, including the filename itself. Is this possible? Thanks.
推荐答案
看看 __file__
.这会为您提供代码实际所在的文件名.
Take a look at __file__
. This gives you a filename where the code actually is.
另外,还有一个选择:
import __main__ as main
print(main.__file__)
这为您提供了正在运行的脚本的文件名(类似于您的argv
所做的).
This gives you a filename of a script being run (similar to what your argv
does).
当代码被另一个脚本导入时,差异就会发挥作用.
The difference comes into play when the code is imported by another script.
这篇关于如何获取python程序的完整路径,包括程序中的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!