I'm making a program that detects python files and reads their classes and functions for then to be called. How do I list the functions from another python file without importing it? and how do I call them?
Structure of the program:
Modules.py list all the python files from /Modules and stores them on a list. Index.py calls the functions in Modules.py (Just to keep things less messy)
ChickenModule.py has a Class named ChickenStuff that prints "I'm a chicken" whenever it's self.(something)
called.
The goal of the program is for the user to be able to put .py files in modules and when running index.py the functions and classes of said .py files will be listed.
There's a built in library called importlib
that might be what you need. I'm assuming that you want classes listed. You'll need inspect
for this.
import os
import os.path as path
import importlib
import inspect
# get a list of all files in Content/Modules
filelist = os.listdir("Content/Modules")
# import every file ending in .py
for fname in filelist:
if path.splitext(fname)[1] == 'py':
my_module = importlib.import_module(path.splitext(fname)[0]) # load the module
for _, obj in inspect.getmembers(my_module): # iterate through members
if isinstance(obj, type): # check if members is a class
print(obj)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments