检查参数是否是 Python 模块? [英] Check if a parameter is a Python module?

查看:18
本文介绍了检查参数是否是 Python 模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何(python 方式)检查参数是否是 Python 模块?没有像模块或包这样的类型.

<预><代码>>>>操作系统<来自'/usr/lib/python2.6/os.pyc'的模块'os'>>>>isinstance(操作系统,模块)回溯(最近一次调用最后一次):文件/usr/lib/gedit-2/plugins/pythonconsole/console.py",第 290 行,在 __run 中r = eval(命令,self.namespace,self.namespace)文件<string>",第 1 行,在 <module> 中NameError:未定义名称模块"

我可以这样做:

<预><代码>>>>类型(操作系统)<输入模块">

但是我拿它比什么呢?:(

我制作了一个简单的模块来快速查找模块中的方法并获取它们的帮助文本.我为我的方法提供了一个模块 var 和一个字符串:

def gethelp(module, sstring):# 这里我需要检查模块是否是模块.对于 listseek(dir(module), sstring) 中的 func:帮助(模块.__dict__[func])

当然,即使 module = 'abc': 然后 dir('abc') 会给我字符串对象的方法列表,但我不需要那个.

解决方案

from types import ModuleTypeisinstance(obj, ModuleType)

How can I (pythonically) check if a parameter is a Python module? There's no type like module or package.

>>> 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:

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.

解决方案

from types import ModuleType

isinstance(obj, ModuleType)

这篇关于检查参数是否是 Python 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆