![](/img/trans.png)
[英]Python - Trying to use the value of a name from one module in a different module
[英]Figure out the module name trying to use imports in one module python
我試圖找出是否有一種方法可以檢測正在嘗試從模塊中導入內容的模塊的名稱,例如,我有一個名為“ all_modules”的模塊,該模塊將我需要的所有導入存儲在整個文件夾中並認為將其導入文件比在我所有文件中多次導入要容易得多,但是通過這樣做,我注意到一旦遇到導入本身,它將停止嘗試導入模塊。 例如,這是我這樣做的總體思路是:
#all_modules.py
import sys, os, time, threading, re, random, urllib.request, urllib.parse
import a, b, c, d # fake modules but general idea is here
# any modules you would need throughout the folder really this is just a small example
#a.py
from all_modules import *
print(sys.version_info) # works fine but lets do the last module
#c.py
from all_modules import *
and_one_more.someFunction("Hello, World!") # it didn't import it because it stopped when it tried to import itself
所以我的想法是找出試圖訪問導入的文件名,然后執行此操作
#all_modules.py - Example two
module_list = ["sys", "os", "time", "threading", "re", "random", "urllib", "urllib.request", "urllib.parse", "a", "b", "c"]
for module in module_list:
if file_name == module: continue # this is what I do not know how to do and not sure if it is even possible, but it's the only solution I have to be able to try to do what I am doing
globals()[module] = __import__(module)
我想知道是否有一些解決方法可以阻止這種情況,還是我必須在每個文件中導入我在整個文件中使用的所有模塊? 就目前而言,我遇到了另一個問題,即沒有導入其他模塊的錯誤,因為在遇到其他模塊之后它沒有導入其余模塊,所以我想知道我想做的事情是否可行,或者解決該問題的方法是否很好,還是我必須在整個文件中單獨導入模塊?
如何從imp
模塊使用load_module
方法:
#!/usr/bin/python
import imp
import sys
def __import__(name, globals=None, locals=None, fromlist=None):
try:
return sys.modules[name]
except KeyError:
pass
fp, pathname, description = imp.find_module(name)
try:
return imp.load_module(name, fp, pathname, description)
finally:
if fp:
fp.close()
module_list = ["sys", "os",
"time", "threading",
"re",
"urllib" ]
for module in module_list:
module = __import__(module)
print module
輸出:
<module 'sys' (built-in)>
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
<module 'time' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/time.so'>
<module 'threading' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.pyc'>
<module 're' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.pyc'>
<module 'urllib' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.pyc'>
您面臨的問題是經典的周期性導入問題。 在python中,解決此問題的最簡單方法是根本不做您正在做的事情,如果您絕對有2個相互依賴的模塊,則可以將模塊作為名稱空間導入,而不必導入其中定義的所有內容(即import x
vs from x import *
)。
通常,*導入在python中不受歡迎,因為其他人不清楚您的代碼中定義了什么的其他人。 基本上是在破壞名稱空間的目的。
您應該真正閱讀PEP8 。 如果您打算將代碼發布到世界上,那么這應該是一個樣式指南。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.