2012-04-24 58 views
8

如果您正在从目录和驱动器运行与脚本存在位置不同的冻结python脚本(使用py2exe冻结),那么确定路径的最佳方法是什么执行脚本?如何获取正在执行的冻结脚本的路径

几个解决方案我已经试过

inspect.getfile(inspect.currentframe()) 

问题:不返回完整路径。它只返回脚本名称。

os.path.abspath(__file__) 

问题:不能在Windows

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

问题的工作:返回空字符串。

os.path.abspath(inspect.getsourcefile(way3)) 

不会,如果驱动器是从PWD不同的工作

os.path.dirname(os.path.realpath(sys.argv[0])) 

如果驱动器是从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 

相关问题:如果脚本驻留在

注意

@ Fenikso的解决方案将工作同样的车程,那里正在执行,但是当它是一个不同的驱动器上,它不会工作

回答

10

另一种方法,甚至使用路径从其它驱动器上运行时与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 

使用PATH:

D:\>pwdme.exe 
h:\Python\Examples\cxfreeze\dist\pwdme.exe 
+2

是的,这也适用于py2exe。 – 2012-04-24 08:50:54

+0

@Fenikso:这很好。在发布这个问题之前,我已经看到很少提及SO中的同一个问题,但是没有一个答案本身是不正确的。 – Abhijit 2012-04-24 09:01:15

0

试试这个:

WD = os.path.dirname(os.path.realpath(sys.argv[0])) 

这就是我与cx_Freeze用于获取从哪里.exe文件所在的目录真的在跑。

+0

如果脚本存在于不同的驱动器 – Abhijit 2012-04-24 08:00:22

+0

@Abhijit这是行不通的 - 对不起,我不明白。这是我所有冻结脚本的基本部分,它从未失败。你能描述一个例子吗? – Fenikso 2012-04-24 08:02:37

+0

我已更新示例以包含此场景。如果驱动器不同,它只是从您正在运行的位置返回驱动器名称。 – Abhijit 2012-04-24 08:06:36

2

恕我直言,根据绝对路径采取不同行为的代码不是一个好的解决方案。 它可能会更好的相对路径解决方案。使用dirname知道相对目录和os.sep的跨平台兼容性。

if hasattr(sys, "frozen"): 
    main_dir = os.path.dirname(sys.executable) 
    full_real_path = os.path.realpath(sys.executable) 
else: 
    script_dir = os.path.dirname(__file__) 
    main_dir = os.path.dirname(os.path.realpath(sys.argv[0])) 
    full_real_path = os.path.realpath(sys.argv[0]) 

冻结属性是python标准。

看看还在ESKY: http://pypi.python.org/pypi/esky

相关问题