天天看點

Python中Package的調用,如需調用__main__.py,必須在__int__.py中加入from .__main__ import *

下面舉個例子:

假設 test_main_py.py 需要調用Package test_main,如需調用__main__.py,必須在__int__.py中加入from .__main__ import *

Python中Package的調用,如需調用__main__.py,必須在__int__.py中加入from .__main__ import *

 test_main_py.py

import os
import sys

_path = os.path.dirname(__file__)
_main_path = '%s/test_main/' % _path
sys.path.insert(1, _main_path)

import test_main
test_main.test_func(a='Hello')           

__init__.py.py

from .__main__ import *           
__main__.py      
def test_func(**kwargs):
    print(kwargs)           

執行後,輸出結果:

Python中Package的調用,如需調用__main__.py,必須在__int__.py中加入from .__main__ import *

假如在__int__.py中沒有加入from .__main__ import *,則會報如下錯誤:

AttributeError: module 'test_main' has no attribute 'test_func'

Python中Package的調用,如需調用__main__.py,必須在__int__.py中加入from .__main__ import *