1

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?

1 Answer 1

3

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

Replace following line:

__import__(data)

with:

globals()[data] = __import__(data)
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, it worked I can't believe I didn't find this on Google before I must have used bad search terms but thank you again that did work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.