【python】__import__

來源:互聯網
上載者:User

標籤: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__

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.