標籤:level 檔案 fun whether pen 系統 function module real
函數定義
__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> moduleImport a module. Because this function is meant for use by the Pythoninterpreter and not for general use it is better to useimportlib.import_module() to programmatically import a module.The globals argument is only used to determine the context;they are not modified. The locals argument is unused. The fromlistshould be a list of names to emulate ``from name import ...‘‘, or anempty list to emulate ``import name‘‘.When importing a module from a package, note that __import__(‘A.B‘, ...)returns package A when fromlist is empty, but its submodule B whenfromlist is not empty. Level is used to determine whether to perform absolute or relative imports. -1 is the original strategy of attemptingboth absolute and relative imports, 0 is absolute, a positive numberis the number of parent directories to search relative to the current module.
name:引用模組名稱,如‘sys’, ‘libs/module.a‘
fromlist:子模組列表,如果name是a.b的格式,則必須把b加入fromlist中
用途
例子
import osdef test(): datetime = __import__(‘datetime‘) print datetime.datetime.now() a = __import__("module.module_a", globals={}, locals={}, fromlist=["module_a"], level=-1) print a.sub(x, y)test()
調用不同目錄的模組
- 應該先sys.path.append(模組所在路徑),然後再用相對路徑引用
例:
在下面這個例子中,由於celery調用,運行路徑跟當前路徑不同,直接引用module.module_a會報錯:無法找到該模組,同時如果__import__的第一個參數用絕對路徑,會報錯:不可使用檔案名稱引用
正確方法就是先在系統路徑中加入當前路徑,然後用相對路徑引用
from celery import Celeryimport osimport syscurrent_path = os.path.dirname(os.path.realpath(__file__))sys.path.append(current_path)app = Celery(‘tasks‘, backend=‘amqp‘, broker=‘amqp://test:[email protected]/testhost‘)@app.taskdef add(x, y): a = __import__("module.module_a", globals={}, locals={}, fromlist=["module_a"], level=-1) print a.add(x, y)
【python】__import__