Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Run a command from a module based on the user's choice

So i have the current code:

module = input('What module?: ')
print(module.run())

& the goal is that it’ll do the run() function of a pre-made module, which module in question is being chosen by the user.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the importlib module to dynamically import the module based on the user’s selection, and then execute the run() method of that module, presuming the module files are in the same directory as the script.

import importlib

module_name = input('Enter module name: ')
try:
    module = importlib.import_module(module_name)
    module.run()
except ModuleNotFoundError:
    print(f"Module {module_name} not found")
except AttributeError:
    print(f"Module {module_name} does not have a run() function")

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading