I'm trying to use inspect.getmembers to check for classes and functions inside a file. The problem is that I don't know how to pass the name of the file to inspect.getmembers without using import. That's because I need to specify a different file name each time

The code looks similar to this:

def extractName(self,fileName):

    for name, obj in inspect.getmembers(FileName):
        if inspect.isclass(obj):

            print "this is class",name


    if inspect.isfunction(obj):

        print "this is method",name
有帮助吗?

解决方案

In order to inspect a module, you must execute it somehow; otherwise, the definitions in the file won't be available.

You can use module = __import__(modname) to import a module by name, or module = imp.load_source("__inspected__", path) to import a module by path.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top