73

假设我有两个模块:

一个.py:

import b
print __name__, __file__

b.py:

print __name__, __file__

我运行“a.py”文件。这打印:

b        C:\path\to\code\b.py
__main__ C:\path\to\code\a.py

问题:如何__main__从“b.py”库中获取模块的路径(在本例中为“a.py”)?

4

5 回答 5

88
import __main__
print(__main__.__file__)
于 2009-03-03T16:04:22.800 回答
40

也许这会奏效:

import sys
from os import path
print(path.abspath(str(sys.modules['__main__'].__file__)))

请注意,为了安全起见,您应该检查__main__模块是否具有__file__属性。如果它是动态创建的,或者只是在交互式 python 控制台中运行,它不会有__file__

python
>>> import sys
>>> print(str(sys.modules['__main__']))
<module '__main__' (built-in)>
>>> print(str(sys.modules['__main__'].__file__))
AttributeError: 'module' object has no attribute '__file__'

一个简单的 hasattr() 检查将起到防范场景 2 的作用,如果这在您的应用程序中是可能的。

于 2009-03-03T14:27:58.427 回答
17

下面的 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-03T20:29:30.587 回答
8

另一种方法是使用sys.argv[0].

import os
import sys

main_file = os.path.realpath(sys.argv[0]) if sys.argv[0] else None

sys.argv[0]如果 Python 开始使用-c或从 Python 控制台检查,则将是一个空字符串。

于 2014-04-05T18:08:36.460 回答
3
import sys, os

def getExecPath():
    try:
        sFile = os.path.abspath(sys.modules['__main__'].__file__)
    except:
        sFile = sys.executable
    return os.path.dirname(sFile)

此函数适用于 Python 和 Cython 编译的程序。

于 2013-01-17T20:57:33.853 回答