检查参数是否是 Python 模块?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1547466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a parameter is a Python module?
提问by culebrón
How can I (pythonically) check if a parameter is a Python module? There's no type like module or package.
我如何(python 方式)检查参数是否是 Python 模块?没有像模块或包这样的类型。
>>> os
<module 'os' from '/usr/lib/python2.6/os.pyc'>
>>> isinstance(os, module)
Traceback (most recent call last):
File "/usr/lib/gedit-2/plugins/pythonconsole/console.py", line 290, in __run
r = eval(command, self.namespace, self.namespace)
File "<string>", line 1, in <module>
NameError: name 'module' is not defined
I can do this:
我可以做这个:
>>> type(os)
<type 'module'>
But what do I compare it to? :(
但是我拿它比什么呢?:(
I've made a simple module to quickly find methods in modules and get help texts for them. I supply a module var and a string to my method:
我制作了一个简单的模块来快速查找模块中的方法并获取它们的帮助文本。我为我的方法提供了一个模块 var 和一个字符串:
def gethelp(module, sstring):
# here i need to check if module is a module.
for func in listseek(dir(module), sstring):
help(module.__dict__[func])
Of course, this will work even if module = 'abc': then dir('abc') will give me the list of methods for string object, but I don't need that.
当然,即使 module = 'abc': 然后 dir('abc') 会给我字符串对象的方法列表,这也会起作用,但我不需要那个。
回答by Lennart Regebro
from types import ModuleType
isinstance(obj, ModuleType)
回答by Denis Otkidach
>>> import inspect, os
>>> inspect.ismodule(os)
True
回答by Greg Hewgill
This seems a bit hacky, but:
这似乎有点hacky,但是:
>>> import sys
>>> import os
>>> type(os) is type(sys)
True
回答by ColdGrub1384
A mix of @Greg Hewgilland @Lennart Regebroanswers:
的混合@格雷格Hewgill和@Lennart Regebro答案:
>>> from types import ModuleType
>>> import os
>>> type(os) is ModuleType
True
回答by Eric Leschinski
Flatten the module to a string and check if it starts with '<module '
将模块展平为字符串并检查它是否以 '<module '
import matplotlib
foobarbaz = "some string"
print(str(matplotlib).startswith("<module ")) #prints True
print(str(foobarbaz).startswith("<module ")) #prints False
Drawback being this could collide with a python string that starts with the text '<module'
You could try to classify it more strongly with a regex.
缺点是这可能会与以文本开头的 python 字符串发生冲突'<module'
您可以尝试使用正则表达式对其进行更强烈的分类。
回答by luoziluojun
Two ways,you could not import any modules:
两种方式,你不能导入任何模块:
type(os) is type(__builtins__)
str(type(os)).find('module')>-1
type(os) is type(__builtins__)
str(type(os)).find('module')>-1