I am having an issue trying to call a function from a variable module.
I have several scripts under a "scripts/" folder, and from outside this folder, I would like to call the main() function of one of my scripts/module inside, but this module name is variable.
Basically, I would like to do this (but this isn't possible in Python apparently):
scripts.{myModuleName}.main()
The
execcommand isn't fitting in my case, as it doesn't wait for the called script to finish properly:exec("scripts." + myModuleName + ".main()")The command
subprocess.runisn't fitting as well because this is calling the full script and not the specificmain()function I want. Andif __name__ == __main__isn't preventing it.my_command = "python scripts\\" + myModuleName subprocess.run(my_command, shell=True, check=True)
Any ideas?
--
EDIT: Thank you Gino, working well with importlib. Here is my code in case it could help someone:
import importlib
import os
#We will get, display and import all the scripts dropped into the 'scripts' folder
moduleList = []
for incr, myScript in enumerate(os.listdir('.\\scripts')):
if ".py" in myScript:
moduleList.append(importlib.import_module(f"scripts.{myScript.replace('.py','')}"))
print(f"{incr+1} - {myScript}")
#Ask the user which script he wants to execute
userChoice = input("Choose the number of the script you want to execute: ")
#Execute the main of the desired script
try:
moduleList[int(userChoice)-1].main()
except (IndexError, ValueError) as e:
print("Error, you need to enter a number displayed above.")
scripts.getattr(myModuleName).main()?