0

i need help to get the name of the not imported module while doing that

so the code is:

#!/usr/bin/env python
bla=[]
try:
    import os
    import sys
    import somethings
    import blabla
except:
    bla.append(NOT_IMPORTED_MODULE_NAME) # it should be here
if len(bla)>0:
    exit("not imported:%s" % " ".join(bla))

thank you in advance

script0r
  • 119
  • 2
  • 9
  • Your code will stop at the first failed import. Your stacktrace will tell you what module will fail. If you really want, you can parse out the string to get the module name. However, this might be a better approach for you: http://stackoverflow.com/questions/14050281/how-to-check-if-a-python-module-exists-without-importing-it – idjaw Feb 26 '16 at 20:06
  • @idjaw so there are no ways to do that? – script0r Feb 26 '16 at 20:10
  • I haven't a found a reason to do this, so I never really over analyzed this. The link I posted seems like what I would do if I wanted to do this. Keep in mind, that if an exception is raised, your code will stop running, so the way your code is written now, it will fail at somethings and won't report blabla. – idjaw Feb 26 '16 at 20:11

2 Answers2

2

Although what I am going to say is more appropriate as comment, I am just typing here since I was not allowed comment due to low reputation number. (since I am very new here)

Let's say you have sys and blabla module missing. With current setting it will throw exception when it tried to load sys. And it will not even reach import blabla. So you wouldn't know if the module missing or not if previous module is missing. If you really really want the feature you want, you can wrap every single import module with exception handling for all module import. But it seems to me that's over kill. As idjaw mentioned, you should be able to see from stacktrace if any module is missing.

Hun
  • 3,707
  • 2
  • 15
  • 15
0
#!/usr/bin/env python
import sys
import os
from importlib import import_module

bla = []

for modulename in ('something', 'blabla'):
    try:
        import_module(modulename)
    except ImportError as exc:
        bla.append(str(exc))


if bla:
    sys.stderr.write('\n'.join(bla))
    sys.stderr.write('\n')
    sys.exit(1)