0

The below code works great to print out what i am trying to do:

#!/usr/bin/env python3
MODULES = [
['termcolor','colored','cprint'],
['signal','signal','SIGINT'],
['some_other_mod','one','two','three','four','five','six','seven','eight']
]

for ITEM in MODULES:
        print("from",'{0} import {1}'.format(ITEM[0],', '.join(str(i) for i in ITEM[1:]))))

When I run the script, it's printed nicely, but unsure how to make it actually do it.

$ ./script.py
from termcolor import colored, cprint
from signal import signal, SIGINT
from some_other_mod import one, two, three, four, five, six, seven, eight

Using exec() with printed format doesn't seem to work. You can see what I am trying to do. If I can list/loop through to import the modules, it would be great.

parsecpython
  • 559
  • 2
  • 5
  • 17
  • 3
    Does this answer your question? [import module from string variable](https://stackoverflow.com/questions/8718885/import-module-from-string-variable) – Zaraki Kenpachi Feb 03 '20 at 06:54
  • What do you mean by exec doesn't work? Did you run `exec(print(...)) `? – MisterMiyagi Feb 03 '20 at 06:55
  • Did you try having a look at importlib? – Eternal Feb 03 '20 at 06:57
  • As this question is closed I have added answer in the existing question here: https://stackoverflow.com/a/60034522/3129414 – arsho Feb 03 '20 at 07:04
  • @mistermiyagi I'd get a 'TypeError: exec() arg 1 must be a string, bytes or code object' error. The links provided in comments fixed the syntax though. Thanks all. – parsecpython Feb 03 '20 at 07:41

0 Answers0