D
D
Dima_E2020-08-02 19:36:01
Python
Dima_E, 2020-08-02 19:36:01

How to re-import a module?

When making changes, you need to re-import the module, but when you re-import the module is ignored, why ?
Example:

import time,traceback,sys,os

file1 = os.path.abspath(os.path.dirname(sys.argv[0]))
sys.path.append(r"{}".format(file1))

if __name__ == '__main__':
    while True:
        try:
            time.sleep(3)
            import Testt
            time.sleep(3)
            print("выход")
        except:
            traceback.print_exc()

The code that is imported simply prints the text.
Its output will be the following:
>>>Working
>>>exit
>>>exit
>>>exit
and so on.
"Works" is a string from the imported code.
Why is this happening and how can I fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Miit, 2020-08-02
@Dima_E

If you need to directly re-invoke the module, then first you need to remove it from the object modulesin the standard library sys, and then re-invoke the import. Or you can use a function reloadfrom the module importlib.
In all other cases, it's better to just declare the function in the module that you need to call.

Examples

import sys
import some_module

del sys.modules['some_module']
import some_module

from importlib import reload
import some_module
reload(some_module)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question