-1

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.

Turb000
  • 11
  • 2
  • There is a way you can import python scripts using a function: https://docs.python.org/3/library/importlib.html#importlib.import_module . If you then have a standardised name for your function, you can just call m.run() if m is the return value of importlib.import_module(module_name) and run is the name of your function – sputnick567 Apr 19 '22 at 14:06

1 Answers1

0

I am not sure I completely understand your question, but here are 2 questions and solutions that might assist

  1. How to import other python files from script? Modules & What is __init__.py for?
  2. Given a string "example" how can I execute the code import example? eval
jsofri
  • 227
  • 1
  • 10
  • I looked into that, that was very helpful thank you. But what i was asking was if there was a good way i could dynamically call functions inside those imported files, such as if i know there is a run function in the script but i don't know the name of the file. again thank you – Turb000 Apr 19 '22 at 15:02
  • @Turb000 you need to import all python files of a specific directory? – jsofri Apr 19 '22 at 15:06