Abh*_*jit 9 python windows path argv
如果您运行的是冷冻python脚本从一个目录(使用py2exe冻结)和驱动从那里脚本存在不同的,什么是确定执行脚本的路径的最佳方式?
我尝试过的解决方案很少
inspect.getfile(inspect.currentframe())
Run Code Online (Sandbox Code Playgroud)
问题:不返回完整路径.它只返回脚本名称.
os.path.abspath( __file__ )
Run Code Online (Sandbox Code Playgroud)
问题:在Windows上不起作用
os.path.dirname(sys.argv[0])
Run Code Online (Sandbox Code Playgroud)
问题:返回空字符串.
os.path.abspath(inspect.getsourcefile(way3))
Run Code Online (Sandbox Code Playgroud)
如果驱动器与pwd不同,则无法工作
os.path.dirname(os.path.realpath(sys.argv[0]))
Run Code Online (Sandbox Code Playgroud)
如果驱动器与pwd不同,则无法工作
这是一个最小的不工作的例子
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
Run Code Online (Sandbox Code Playgroud)
相关问题:
注意
如果脚本位于您正在执行的同一个驱动器上但是当它位于不同的驱动器上时,@ Fenikso的解决方案将起作用,它将无法工作
Fen*_*kso 11
另一种方法,即使使用PATH从另一个驱动器运行时也可以使用cxFreeze:
import sys
if hasattr(sys, 'frozen'):
print(sys.executable)
else:
print(sys.argv[0])
Run Code Online (Sandbox Code Playgroud)
来自Python:
H:\Python\Examples\cxfreeze\pwdme.py
Run Code Online (Sandbox Code Playgroud)
从命令行:
D:\>h:\Python\Examples\cxfreeze\dist\pwdme.exe
h:\Python\Examples\cxfreeze\dist\pwdme.exe
Run Code Online (Sandbox Code Playgroud)
使用PATH:
D:\>pwdme.exe
h:\Python\Examples\cxfreeze\dist\pwdme.exe
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5322 次 |
最近记录: |