import os
import re
def find_runfiles():
"""Find the runfiles tree (useful when _not_ run from a zip file)"""
# Follow symlinks, looking for my module space
stub_filename = os.path.abspath(sys.argv[0])
while True:
# Found it?
module_space = stub_filename + '.runfiles'
if os.path.isdir(module_space):
break
runfiles_pattern = r"(.*\.runfiles)"
matchobj = re.match(runfiles_pattern, os.path.abspath(sys.argv[0]))
if matchobj:
module_space = matchobj.group(1)
break
raise RuntimeError('Cannot find .runfiles directory for %s' %
sys.argv[0])
return module_space
更恰当的答案是使用Bazel提供的runfiles库,该库位于https://github.com/bazelbuild/bazel/blob/master/tools/python/runfiles/runfiles.py
请参阅文件开头的用法部分。在
以下是一个函数,在我所知的所有情况下,它应该返回任何py_二进制文件的runfiles根路径:
对于问题中的示例,您可以这样使用:
^{pr2}$请注意,如果您构建python应用程序的压缩可执行文件(可能使用subpar),那么这个函数将不会有帮助;对于这些应用程序,您需要更多的代码。下一个代码片段包括
get_resource_filename()
和get_resource_directory()
,这两个代码既适用于常规py二进制文件,也适用于.par二进制文件:使用第二个代码片段,您的示例将如下所示:
简短回答:
os.path.dirname(__file__)
以下是完整的示例:
编辑:当你的包在子目录中时,它不能很好地工作。您可能需要使用
os.path.dirname
返回。在相关问题 更多 >
编程相关推荐