[英]How to get filename of the __main__ module in Python?
假設我有兩個模塊:
a.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
問題 :如何從“b.py”庫中獲取__main__
模塊的路徑(本例中為“a.py”)?
import __main__
print __main__.__file__
也許這會解決問題:
import sys
from os import path
print path.abspath(sys.modules['__main__'].__file__)
請注意,為了安全起見,您應該檢查__main__
模塊是否具有__file__
屬性。 如果它是動態創建的,或者只是在交互式python控制台中運行,它將沒有__file__
:
python
>>> import sys
>>> print sys.modules['__main__']
<module '__main__' (built-in)>
>>> print sys.modules['__main__'].__file__
AttributeError: 'module' object has no attribute '__file__'
如果您的應用程序中存在這種可能性,那么簡單的hasattr()檢查就可以防范方案2。
下面的python代碼提供了額外的功能,包括它與py2exe
可執行文件無縫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')
希望上面的示例代碼可以提供有關如何確定正在運行的腳本的路徑的其他信息......
另一種方法是使用sys.argv[0]
。
import os
import sys
main_file = os.path.realpath(sys.argv[0]) if sys.argv[0] else None
如果Python以-c
開頭或從Python控制台檢查,則sys.argv[0]
將為空字符串。
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編譯的程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.