![](/img/trans.png)
[英]How to selectively import only lines of words with genfromtxt into Python?
[英]How to selectively import module in python?
我有幾個不同的模塊,我需要根據不同的情況導入其中一個,例如:
if check_situation() == 1:
import helper_1 as helper
elif check_situation() == 2:
import helper_2 as helper
elif ...
...
else:
import helper_0 as helper
這些助手包含相同的詞典dict01
, dict02
, dict03
......但是在不同情況下要調用不同的值。
但這有一些問題:
check_situation()
函數在這里需要先決條件,所以它現在遠遠不是頂部。 那么,如何重新安排這些助手呢?
您可以使用__import__()
,它接受一個字符串並返回該模塊:
helper=__import__("helper_{0}".format(check_situation()))
例如:
In [10]: mod=__import__("{0}math".format(raw_input("enter 'c' or '': ")))
enter 'c' or '': c #imports cmath
In [11]: mod.__file__
Out[11]: '/usr/local/lib/python2.7/lib-dynload/cmath.so'
In [12]: mod=__import__("{0}math".format(raw_input("enter 'c' or '': ")))
enter 'c' or '':
In [13]: mod.__file__
Out[13]: '/usr/local/lib/python2.7/lib-dynload/math.so'
正如@wim和__import__()
上的__import__()
docs所指出的那樣:
導入模塊。 因為此函數適用於Python解釋器而不是一般用途,所以最好使用
importlib.import_module()
以編程方式導入模塊。
首先,沒有嚴格要求import語句需要位於文件的頂部,它更像是一個樣式指南。
現在, importlib
和dict
可用於替換if
/ elif
鏈:
import importlib
d = {1: 'helper_1', 2: 'helper_2'}
helper = importlib.import_module(d.get(check_situation(), 'helper_0'))
但它真的只是語法糖,我懷疑你有更大的魚來炸。 聽起來你需要重新考慮你的數據結構,並重新設計代碼。
任何時候你有一個名為變量一樣dict01
, dict02
, dict03
那就是你需要齒輪上升了一個層次一個明確的信號,並有一些容器dicts
,例如它們的列表。 您的'helper'模塊名稱以數字結尾也是如此。
我同意其他答案中給出的方法更接近標題中提出的主要問題,但如果導入模塊的開銷很低(因為可能導入幾個字典)並且導入沒有副作用,在這種情況下,您可能最好將它們全部導入並在模塊中稍后選擇正確的字典:
import helper_0
import helper_1
...
helperList = [helper_0, helper_1, helper_2...]
...
helper = helperList[check_situation()]
自己解決,提到@Michael Scott Cuthbert
# re_direct.py
import this_module
import that_module
wanted = None
# caller.py
import re-direct
'''
many prerequisites
'''
def imp_now(case):
import re_direct
if case1:
re_direct.wanted = re_direct.this_module
elif case2:
re_direct.wanted = re_direct.that_module
然后,如果在調用者中,我調用imp_now,然后想要,無論調用調用者文件或其他調用此文件的文件,都將被重定向到this_or_that_module。
另外,因為我只在一個函數中導入re_direct,所以你不會在其他地方看到這個模塊,但只看到想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.