我怎么能知道是否存在一个没有进口的甲粉碎模块?
进口可能不存在的东西(并非我想要的东西)导致:
try:
import eggs
except ImportError:
pass
我怎么能知道是否存在一个没有进口的甲粉碎模块?
进口可能不存在的东西(并非我想要的东西)导致:
try:
import eggs
except ImportError:
pass
TL;DR) Use importlib.util.find_spec(module_name)
(Python 3.4+)。
imp.find_module
查看imp
2>查询。
import imp
try:
imp.find_module( eggs )
found = True
except ImportError:
found = False
为了找到有标识的进口产品,你需要做更多的工作:
import imp
try:
spam_info = imp.find_module( spam )
spam = imp.load_module( spam , *spam_info)
imp.find_module( eggs , spam.__path__) # __path__ is already a list
found = True
except ImportError:
found = False
You can also use pkgutil.find_loader
(more or less the same as the Python 3 part:
import pkgutil
eggs_loader = pkgutil.find_loader( eggs )
found = eggs_loader is not None
importlib.find_loader
您应使用<条码>进出口<>。 我这样做了:
import importlib
spam_loader = importlib.find_loader( spam )
found = spam_loader is not None
我期望,如果你能够找到装备,那么就存在。 你们也可以更精彩地对待它,例如过滤你将接受的装载器。 例如:
import importlib
spam_loader = importlib.find_loader( spam )
# only accept it as valid if there is a source file for the module - no bytecode only.
found = issubclass(type(spam_loader), importlib.machinery.SourceFileLoader)
importlib.util.find_spec
http://docs.python.org/3/library/importlib.html 涂 Python文件,改成importlib.util.find_spec
。 建议的方法是<编码> 进口校准。 还有其他一些问题,如:importlib.pednery.FileFinder
,如果你在具体档案之后再加装,那是有用的。 证明如何使用这些工具超出了这一范畴。
import importlib.util
spam_spec = importlib.util.find_spec("spam")
found = spam_spec is not None
这还涉及相对进口,但你必须提供一揽子起点,因此,你还可以:
import importlib.util
spam_spec = importlib.util.find_spec("..spam", package="eggs.bar")
found = spam_spec is not None
spam_spec.name == "eggs.spam"
虽然我确信有这样做的理由,但我不敢肯定会做些什么。
在试图找到一个小单元时,它将进口母体模块(用于
food/
|- __init__.py
|- eggs.py
## __init__.py
print("module food loaded")
## eggs.py
print("module eggs")
were you then to run
>>> import importlib
>>> spam_spec = importlib.util.find_spec("food.eggs")
module food loaded
ModuleSpec(name= food.eggs , loader=<_frozen_importlib.SourceFileLoader object at 0x10221df28>, origin= /home/user/food/eggs.py )
接下<>
find_loader
The ModuleNotFoundError
has been introduced in Python 3.6 and can be used for this purpose:
try:
import eggs
except ModuleNotFoundError:
# Error handling
pass
当无法找到或其父母之一时,就会产生错误。 So
try:
import eggs.sub
except ModuleNotFoundError as err:
# Error handling
print(err)
打印一个像<代码>的信息。 如果eggs
,则没有名为蛋类的模块。 模块无法找到,但如<代码>。 不含蛋类的模块,但只有<代码>><>/code>。 模块可找到,但<代码>eggs的包裹可找到。
见 进口系统的文件,以了解有关<编码>的更多信息。 模块NotFoundError。
在使用之后,我这样就不必进口
try:
__import__( imp ).find_module( eggs )
# Make things with a supposed existing module
except ImportError:
pass
在Django s,例如:py文档。
直到更新目前的答案为止,这里是Python 2的道路。
import pkgutil
import importlib
if pkgutil.find_loader(mod) is not None:
return importlib.import_module(mod)
return None
很多答复都使用了<代码>ImportError。 问题在于,我们不能知道什么扔下了<代码>。 ImportError。
如果您进口<>存在于<><><>>><>>><>>>> 模块,如在(例如,第1行的打字)上出现<> 代码> /代码>,其结果将是,你的模块不存在。
将请你说明,你的模块已经存在,而<代码>ImportError被抓住,使事情无声地失败。
python -c "help( modules );" | grep module
Use one of the , for example:
from pkgutil import iter_modules
def module_exists(module_name):
return module_name in (name for loader, name, ispkg in iter_modules())
我写了这一助手职能:
def is_module_available(module_name):
if sys.version_info < (3, 0):
# python 2
import importlib
torch_loader = importlib.find_loader(module_name)
elif sys.version_info <= (3, 3):
# python 3.0 to 3.3
import pkgutil
torch_loader = pkgutil.find_loader(module_name)
elif sys.version_info >= (3, 4):
# python 3.4 and above
import importlib
torch_loader = importlib.util.find_spec(module_name)
return torch_loader is not None
这里可以检查一个模块是否从command Line装载:
HCH/UNIX 文字档案方法: a 文档module_help.py
:
#!/usr/bin/env python
help( modules )
然后,确保执行:<代码>chmod u+x 模块_help.py
And call it with a pipe
to grep
:
./module_help.py | grep module_name
Invoke thebuilding-in 。 (这一职能为,用于互动使用)。 如果没有争辩,交互求助系统就在口译专线上开始。 如果这一论点是strong>strong>,那么该说明将作为module、功能、类别、方法、关键词或文件专题的名称,而帮助页则在专栏上印发。 如果这一论点是任何其他物体,则在物体上生成一个帮助页。
<>Interactive methods: in the console,load python
>>> help( module_name )
If found, quit reading by typing q
.
To exit the Python interpreter interactive session, press Ctrl + D
Windows script file method, also Linux/UNIX compatible, and better overall:
#!/usr/bin/env python
import sys
help(sys.argv[1])
从指挥部门接手:
python module_help.py site
产出:
帮助模块现场:
NAME
site - Append module search paths for third-party packages to sys.path.
FILE
/usr/lib/python2.7/site.py
MODULE DOCS
http://docs.python.org/library/site
DESCRIPTION
... :
And you d have to press q
to exit interactive mode.
Using it for an unknown module, e.g.,
python module_help.py lkajshdflkahsodf
产出:
没有为Lkajshdflkahsodf找到的灰色文件
离开。
你只能写几本,试图进口所有单元,告诉你哪些单元失败,哪些单元正在发挥作用:
import pip
if __name__ == __main__ :
for package in pip.get_installed_distributions():
pack_string = str(package).split(" ")[0]
try:
if __import__(pack_string.lower()):
print(pack_string + " loaded successfully")
except Exception as e:
print(pack_string + " failed with error code: {}".format(e))
产出:
zope.interface loaded successfully
zope.deprecation loaded successfully
yarg loaded successfully
xlrd loaded successfully
WMI loaded successfully
Werkzeug loaded successfully
WebOb loaded successfully
virtualenv loaded successfully
...
警告词:这将试图进口PyYAML”这样的物品有误: 由于实际进口名称仅为yaml,因此没有称为pyyaml
的模块。 只要知道你的进口,这就应该为你们 do。
如果“配制的模块”在进口时不进口母体,则没有任何可靠检查的方法。 由此可见,有许多解决办法可以解决“如果存在“灰尘”问题。
下面的解决办法涉及进口模块即使存在也会产生进口出价的问题。 我们要区分这种局面与单元不存在的情况。
<><>Python 2:>
import importlib
import pkgutil
import sys
def find_module(full_module_name):
"""
Returns module object if module `full_module_name` can be imported.
Returns None if module does not exist.
Exception is raised if (existing) module raises exception during its import.
"""
module = sys.modules.get(full_module_name)
if module is None:
module_path_tail = full_module_name.split( . )
module_path_head = []
loader = True
while module_path_tail and loader:
module_path_head.append(module_path_tail.pop(0))
module_name = ".".join(module_path_head)
loader = bool(pkgutil.find_loader(module_name))
if not loader:
# Double check if module realy does not exist
# (case: full_module_name == paste.deploy )
try:
importlib.import_module(module_name)
except ImportError:
pass
else:
loader = True
if loader:
module = importlib.import_module(full_module_name)
return module
<>Python 3
import importlib
def find_module(full_module_name):
"""
Returns module object if module `full_module_name` can be imported.
Returns None if module does not exist.
Exception is raised if (existing) module raises exception during its import.
"""
try:
return importlib.import_module(full_module_name)
except ImportError as exc:
if not (full_module_name + . ).startswith(exc.name + . ):
raise
在django.utils.module_loading.module_has_submodule:
import sys
import os
import imp
def module_has_submodule(package, module_name):
"""
check module in package
django.utils.module_loading.module_has_submodule
"""
name = ".".join([package.__name__, module_name])
try:
# None indicates a cached miss; see mark_miss() in Python/import.c.
return sys.modules[name] is not None
except KeyError:
pass
try:
package_path = package.__path__ # No __path__, then not a package.
except AttributeError:
# Since the remainder of this function assumes that we re dealing with
# a package (module with a __path__), so if it s not, then bail here.
return False
for finder in sys.meta_path:
if finder.find_module(name, package_path):
return True
for entry in package_path:
try:
# Try the cached finder.
finder = sys.path_importer_cache[entry]
if finder is None:
# Implicit import machinery should be used.
try:
file_, _, _ = imp.find_module(module_name, [entry])
if file_:
file_.close()
return True
except ImportError:
continue
# Else see if the finder knows of a loader.
elif finder.find_module(name):
return True
else:
continue
except KeyError:
# No cached finder, so try and make one.
for hook in sys.path_hooks:
try:
finder = hook(entry)
# XXX Could cache in sys.path_importer_cache
if finder.find_module(name):
return True
else:
# Once a finder is found, stop the search.
break
except ImportError:
# Continue the search for a finder.
continue
else:
# No finder found.
# Try the implicit import machinery if searching a directory.
if os.path.isdir(entry):
try:
file_, _, _ = imp.find_module(module_name, [entry])
if file_:
file_.close()
return True
except ImportError:
pass
# XXX Could insert None or NullImporter
else:
# Exhausted the search, so the module cannot be found.
return False
如果你知道档案的位置,并想要核实有关“灰色”密码档案是否有该单元,那么你可以简单地通过>在A/63/1中进行包装。 这方面的例子很迅速:
"""
Check if a module function exists or not without importing a Python package file
"""
import ast
import astor
tree = astor.parse_file( handler.py )
method_to_check = handle
for item in tree.body:
if isinstance(item, ast.FunctionDef):
if item.name == method_to_check:
print( method exists )
break
也可使用<条码>进出口。 直接
import importlib.util
def module_exists_without_import(module_name):
spec = importlib.util.find_spec(module_name)
return spec is not None
http://askubuntu.com/questions/588390 我如何检查一个单元是否安装在:
import sys
print( eggs in sys.modules)
我测试了这里提供的一些解决办法,但有些解决办法截至今天已经过时:12/22/2023。 这里,我为jupyter lab下的Pyton 3.12.1实施和测试:
""" Downloads competition files from Kaggle assuming you previously downloaded the
kaggle.json file and put in the location indicated here:
https://github.com/Kaggle/kaggle-api?tab=readme-ov-file#api-credentials.
It unzips the files and place them in th e dataDir location. If the folder contains
information it deletes it before, Once the information is unziped,
it removes the zip file"""
def downloadInputData(competitionName, dataDir= input ):
import os,importlib.util
if importlib.util.find_spec( kaggle ) is not None:
! pip install kaggle --quiet
import kaggle
kaggle.api.authenticate() # raise an error if the kaggle.json is not the expected location
# download and unzip competition data
! rm -rf {dataDir} # removing data files if they exist
! kaggle competitions download -q {competitionName} # -q for quite download
! mkdir -p {dataDir}
zipFile = competitionName + .zip
if not os.path.exists(zipFile):
print(f"Error: , {zipFile}, not found.")
else:
# -q silent option (no output), concatenate rm to remove the zip file
! unzip -q {zipFile} -d {dataDir} && rm {zipFile}
# Testing
competitionName = titanic
downloadInputData(competitionName=competitionName)
Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...
I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...
Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...
Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...
I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...
Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...
Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...
I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...