1

I am trying to implement a python program that analyzes python source files in a given directory and produces class dependency list, along with the source filename in which the class definition is found, in the following format.

Class name1 [filename]
 Derived Classname1 [filename]
 Derived Classname2 [filename]
 Derived Classname3 [filename]
 …
 Class name2 [filename]
 Derived ClassnameA [filename]
 Derived ClassnameB[filename]
 Derived ClassnameC [filename]

I could not figure out the logic. Code to read the files from directory is given below is there a module for inheritance logic in python? cmd command: >>python cs2.py "C:\Users\PC-server\Documents\PythonCode\dir1"

cs2.py

import sys
import os
def processFiles(path):
    try: 
        fileList = os.listdir(path)
        for i in fileList:
            filePath= path +"\\"+i;
            if(os.path.isfile(filePath)):
                fileName = i;
                print(filePath)
                file = open(filePath, 'r')
                #logic will go here
            #file.close()
    except: 
        print('Error reading the directory')
def main(argv):
   processFiles(argv)
main(sys.argv[1])
3
  • are you looking to get all python files in a dir ?? Commented Nov 28, 2021 at 6:55
  • 1
    and if you want to know the base classes of a class what you need to do is ast parsing. docs.python.org/3/library/ast.html Commented Nov 28, 2021 at 6:58
  • 1
    If you want to do it without a module, you can always read the file, check for lines which begin with the class keyword (after stripping whitespace, of course), and then parse those. Commented Nov 28, 2021 at 7:08

1 Answer 1

1

So after a lot of researching and after spending two days on this I am able to achieve the desired result by breaking the problems in parts and combining chunk of code from various stack over flow questions

I have just starting learning python and obviously the code could be written more efficiently. But at present I am happy with the result.

#python cs2.py "C:\Users\PC-server\Documents\PythonCode\testClasses"
import sys
import os
import ast  
import inspect

def importClasses(path,fileList):
    sys.path.append(path)    
    for i in fileList:
        filePath= path +"\\"+i;
        if(os.path.isfile(filePath)):
            fileName = i
            name, ext = os.path.splitext(fileName)
            module = __import__(name)
            globals()[name] = module
            
def printSubClassResult(className):
    subclasses = eval(className).__subclasses__()
    for cls in subclasses:
        classFileName = os.path.basename(inspect.getmodule(cls).__file__)
        print("\t",cls.__name__, "[", classFileName, "]")    

def printClassResult(path,fileList):
    for i in fileList:
            filePath= path +"\\"+i;
            if(os.path.isfile(filePath)):
                fileName = i
                name, ext = os.path.splitext(fileName)
                file = open(filePath, "r")
                code = file.read()
                tree = ast.parse(code)
                classes = [node for node in ast.walk(tree) if isinstance(node, ast.ClassDef)]
                for classObj in classes:
                    print(classObj.name, "[", fileName, "]")
                    className = name + "."+ classObj.name
                    printSubClassResult(className)
                    print("\n")
                    
def processFiles(path):
    
    try:
        fileList = os.listdir(path)
        
        importClasses(path,fileList)
        
        printClassResult(path,fileList)
        
    except BaseException as err:
        print(f"Unexpected {err=}, {type(err)=}")
    
def main(argv):
   processFiles(argv)
   
main(sys.argv[1])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.