How to import a python module after downloading it from the same python program

What I am trying to do is that I have a simple python program which print the the key which I pressed right now so for that I am doing is it thorough pynput module and if it is not available than download it from the internet. But when I download it I needed to restart the code to get worked properly.

HERE IS THE CODE:-

import os  

def download_it():
    try:
        os.system('pip3 install pynput') 
        from pynput.keyboard import Key, Listener
    except:
        download_it()   #this will rerun the code it there is not internet connection or some failure happen

try:
    from pynput.keyboard import Key, Listener
except:
    download_it()

def on_press(key):
    print(key)

with Listener(on_press=on_press) as listener:
    listener.join()

Is there any way so that i need not to restart the code to get it worked.

Upvotes: 1

Views: 80

Answers (1)

Cheukting
Cheukting

Reputation: 264

Your answer is in the importlib module I believe.

Note that in import_module:

If you are dynamically importing a module that was created since the interpreter began execution (e.g., created a Python source file), you may need to call invalidate_caches() in order for the new module to be noticed by the import system.

Upvotes: 1

Related Questions