find out whether a module exists (without importing it)
Gelonida N
gelonida at gmail.com
Tue Aug 7 04:00:16 EDT 2012
Hi Michael,
On 08/07/2012 08:43 AM, Michael Poeltl wrote:
> in my opinion, "without importing it" makes it unnecessarily complicated.
It does, but I think this is what I want, thus my question.
I tried to keep my question simple without explaining too much.
Well now here's a little more context.
There's two reasons why I sepcified the without importing it.
Some modules may have side effects when being imported,and sometimes I
just want to check for a module's existence
Second:
Sometimes I only want to know, whether a module exists.
I do not want to know whether a module is syntactically correct or
whether a module if imported is capable of
importing all it's submodules
What I'd like to achieve at the moment is to distinguish three situations:
- a module with a given name does not exist
- a module with a given name exists and produces errors (might be
ImportErors)
- a module with a given name exists and can be imported
In fact what I really want to achieve is:
import a module if it exists (and fail if it is broken)
if it doesn't exist import a 'default' module and go on.
The name of the module is stored in a variable and is not known prior to
running the script so the code, that you suggested would be something like.
modulename = 'my.module'
cmd = 'import %s as amodule'
try:
exec(cmd)
print "imported successfully"
except ImportError:
print "module doesn't exist or the module tries to " \
"import another module that doesn't exist"
# if the module doesn't exist I'd like to import a 'fallback' module
# otherwise I'd like to abort.
except Exception as exc:
print "module exists, but is broken"
raise exc
amodule.do_something()
> You just want to know it module xyz exists, or better said can be found
> (sys.path).
>
> why not try - except[ - else ]
>
> try:
> import mymodule
> except ImportError:
> # NOW YOU KNOW it does not exist
> #+ and you may react properly
> ??
> * Gelonida N <gelonida at gmail.com> [2012-08-06 22:49]:
>> Is this possible.
>>
>> let's say I'd like to know whether I could import the module
>> 'mypackage.mymodule', meaning,
>> whther this module is located somewhere in sys.path
>>
>> i tried to use
>>
>> imp.find_module(), but
>> it didn't find any module name containing a '.'
>>
>> Am I doing anything wrong?
>>
>> Is there another existing implementation, that helps.
>>
>> I could do this manually, but this is something I'd just like to do
>> if necessary.
>>
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list