I want to be able to import the contents of a folder and be able to call functions in classes inside them by name, like say i have example.py i would want to be able to type 'example' with python input commands and be able to run a function inside it
To achieve this I was thinking of maybe using objects such as this but i have really no idea where to start or what best practice would be.
class File():
def __init__(self, name):
self.name = name
def run()
dostuff()
i was also thinking maybe something like this would work for calling it:
files = []
for i in files:
if i.name == name:
i.run()
I have no idea how I would import the entire file and be able to extract it to a list. All I want to do is just be able to import all files into a folder and be able to run them by name.
I searched on the internet for a while attempting to find an answer to this but couldn't find much that was helpful so any help would be greatly appreciated.
CodePudding user response:
I am not sure I completely understand your question, but here are 2 questions and solutions that might assist
- How to import other python files from script? Modules & What is __init__.py for?
- Given a string
"example"
how can I execute the codeimport example
? eval
CodePudding user response:
You can use __import__
. It is very similar to the import
keyword, but __import__
is a function you can pass string values to. If you don't know what modules are, then check out this link.