ruler
ruler

Reputation: 623

Dynamically import a module

How do I keep a import without restarting the program and manually doing it?

I have tried this:

class runProgram:
    def cmdEval(self,data):
        try:
            return str(repr(eval(data)))
        except Exception as e:
            return e
    def cmdImport(self,data):
        try:
            __import__(data)
            return "Imported."
        except: 
                return "Error to import"
    def run(self):
        while True:
            command = input("Command: ")
            command,data = command.split(" ",1)
            if command == "ev": print(self.cmdEval(data))
            elif command == "imp": print(self.cmdImport(data))

Then I did the following:

>>> runProgram().run()
Command: imp time
Imported.
Command: ev time.time()
name 'time' is not defined

The result did not work, as I expected it not to but is their away to dynamically import without the use of saving the data? I mean I want to be able to use it but I don't want it their after I restart I just want to be able to have it there incase I need to import something for that particular session So for example this would be the desired results I want,

imp time
ev time.time()
>1383535034.20894
>>> ================================ RESTART ================================
>>> time.time()
Traceback (most recent call last):
  File "<pyshell#238>", line 1, in <module>
    time.time()
NameError: name 'time' is not defined

Is this possible?

Upvotes: 1

Views: 114

Answers (1)

falsetru
falsetru

Reputation: 369384

__import__ returns the imported module, and does not change the global namespace.

Replace following line:

__import__(data)

with:

globals()[data] = __import__(data)

Upvotes: 3

Related Questions