2

我有一个 python 文件列表。我需要使用 inpect 获取所有方法,例如函数

E.g. mylist = ['/path/to/myfle.py']

   /path/to/myfle.py
    def foo():
       return 'bar'
    def bar():
       return 'foo'

如果给定文件名和路径,如何获取方法列表?

for file in mylist:
    ????



#The file exists
ls /home/ubuntu/workspace/ndkt-scraper/src/parsers/pacer/parser_pacer_file.py
/home/ubuntu/workspace/ndkt-scraper/src/parsers/pacer/parser_pacer_file.py

strs = '/home/ubuntu/workspace/ndkt-scraper/src/parsers/pacer/parser_pacer_file.py'
path, _ = os.path.splitext(strs)               #now path is '/path/to/myfile'
file_name = path.split('/')[-1]                # returns myfile]
mod = importlib.import_module(file_name, path)

Traceback (most recent call last):
  File "/home/ubuntu/workspace/ndkt-scraper/src/crawler.py", line 31, in <module>
    mod = importlib.import_module(file_name, path)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named parser_pacer_file


parser_pacer_file.py
def parser_pacer_method(html):

    data = {'foo':'bar'}

    return data
4

2 回答 2

5

用于使用importlib路径导入模块,然后使用types模块从导入的模块中过滤掉函数。

>>> import os
>>> import types
>>> import importlib
>>> strs = '/path/to/myfle.py'
>>> path, _ = os.path.splitext(strs)               #now path is '/path/to/myfile'
>>> file_name = path.split('/')[-1]                # returns myfile
>>> mod = importlib.import_module(file_name, path)
>>> funcs = [x for x in dir(mod) if isinstance(getattr(mod,x), types.FunctionType)]
>>> funcs
['foo', 'func']  #name of functions
于 2013-06-15T07:31:22.243 回答
0

你需要使用importdir()

于 2013-06-15T07:31:11.727 回答