如果您从与脚本所在的目录和驱动器不同的目录和驱动器运行卡住的 python 脚本(使用 py2exe 卡住),确定执行脚本路径的最佳方法是什么?
我尝试过的几个解决方案
inspect.getfile(inspect.currentframe())
问题:不返回完整路径。它只返回脚本名称。
os.path.abspath( __file__ )
问题:在 Windows 上不工作
os.path.dirname(sys.argv[0])
问题:返回空字符串。
os.path.abspath(inspect.getsourcefile(way3))
如果驱动器与密码不同,将无法工作
os.path.dirname(os.path.realpath(sys.argv[0]))
如果驱动器与密码不同,将无法工作
这是一个最小的不工作的例子
D:\>path
PATH=c:\Python27\;c:\Users\abhibhat\Desktop\ToBeRemoved\spam\dist\;c:\gnuwin32\bin
D:\>cat c:\Users\abhibhat\Desktop\ToBeRemoved\spam\eggs.py
import os, inspect, sys
def way1():
return os.path.dirname(sys.argv[0])
def way2():
return inspect.getfile(inspect.currentframe())
def way3():
return os.path.dirname(os.path.realpath(sys.argv[0]))
def way4():
try:
return os.path.abspath( __file__ )
except NameError:
return "Not Found"
def way5():
return os.path.abspath(inspect.getsourcefile(way3))
if __name__ == '__main__':
print "Path to this script is",way1()
print "Path to this script is",way2()
print "Path to this script is",way3()
print "Path to this script is",way4()
print "Path to this script is",way5()
D:\>eggs
Path to this script is
Path to this script is eggs.py
Path to this script is D:\
Path to this script is Not Found
相关问题:
- How to know the path of the running script in Python?
- How do I get the path and name of the file that is currently executing?
- python, path of script [closed]
注意
@Fenikso 的解决方案如果脚本驻留在您正在执行的同一驱动器上将起作用,但当它位于不同的驱动器上时,它将不起作用
最佳答案
即使使用 PATH 从另一个驱动器运行时,也可以使用 cxFreeze 的另一种方法:
import sys
if hasattr(sys, 'frozen'):
print(sys.executable)
else:
print(sys.argv[0])
来自 Python:
H:\Python\Examples\cxfreeze\pwdme.py
从命令行:
D:\>h:\Python\Examples\cxfreeze\dist\pwdme.exe
h:\Python\Examples\cxfreeze\dist\pwdme.exe
使用路径:
D:\>pwdme.exe
h:\Python\Examples\cxfreeze\dist\pwdme.exe
关于python - 如何获取执行卡住脚本的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10293808/