下面的python代码提供了额外的功能,包括它可以与py2exe
可执行文件无缝协作。
我使用类似的代码来找到相对于运行脚本的路径,即__main__
。作为一个额外的好处,它可以运行包括Windows在内的跨平台。
import imp
import os
import sys
def main_is_frozen():
return (hasattr(sys, "frozen") or # new py2exe
hasattr(sys, "importers") # old py2exe
or imp.is_frozen("__main__")) # tools/freeze
def get_main_dir():
if main_is_frozen():
# print 'Running from path', os.path.dirname(sys.executable)
return os.path.dirname(sys.executable)
return os.path.dirname(sys.argv[0])
# find path to where we are running
path_to_script=get_main_dir()
# OPTIONAL:
# add the sibling 'lib' dir to our module search path
lib_path = os.path.join(get_main_dir(), os.path.pardir, 'lib')
sys.path.insert(0, lib_path)
# OPTIONAL:
# use info to find relative data files in 'data' subdir
datafile1 = os.path.join(get_main_dir(), 'data', 'file1')
希望上面的例子可以提供额外的洞察如何确定正在运行的脚本的路径...
它的确 - 谢谢! – 2009-03-03 14:29:54
Wunderbar!我很高兴能够提供帮助。如果这确实回答你的问题,你会介意在问题上点击“接受”按钮吗? :-) – 2009-03-03 14:33:01
如果你编辑这个以使用“import __main__”风格,我会变回被接受的,因为这比新接受的答案更详细。 – 2009-03-03 16:57:50