Question

I have a some bunch of python files. I need to get all the classes from there and make a list. its like I have to read with streamreader and then

Imports ActionBlock

I have to take the string ActionBlock and show it in a list. Listing and others hopefully I can do, but I am stuck in this point. Any suggestion please? Thank you.

Was it helpful?

Solution

You could use a regular expression to look for the parts you're interested in.

The following code

Dim path = "c:\path\to\your\file.py"
Dim content = File.ReadAllText(path)

Dim matchClass = "class (?<m>\w+)(:|\()+"
Dim matchImport = "(^|from \w+ )import ((?<m>\w+), )*(?<m>\w+)"

Dim result = Regex.Matches(content, String.Format("({0}|{1})", matchClass, matchImport), RegexOptions.Multiline) _
                  .Cast(Of Match) _
                  .SelectMany(Function(m) m.Groups("m").Captures.Cast(Of Capture).Select(Function(c) c.Value)) _
                  .ToList() 

will, given a text file like

import os 
import math 
from time import clock 
from random import randint 
import DataArchiving 
import TABasicFunctions 
import HWDataConveterGate 
import GeneralTestDataMapping
from something import FirstClass, SecondClass

def foo():
    pass

def bar():
    pass

class ClassOne(object):
    class NestedClass:
        pass

    def thisisnotaclass(self):
        v = [x.class for x in self]
        v = [x.someimport for x in self]

class ClassTwo:
    pass

class Class3:
    pass

def main():
    pass

if __name__ == '__main__':
    main()

create a list that looks like:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top