获取当前文件中的协程列表
Get list of Coroutines in current file
我想获取当前文件中所有协程的列表(extern_method 和 extern_method2 在我的代码示例中)。行为应与:method_list = [extern_method, extern_method2]
相同,但我希望它自动列出。
我有这样的文件结构:
@wraps(lambda: extern_method)
@my_decorator
async def extern_method(arg)
return arg + "hello"
@wraps(lambda: extern_method2)
@my_decorator
async def extern_method2(arg)
return arg + 123
class myclass:
(...)
def find_extern_methods():
#here missing code
return method_list
(...)
def do_sth_with_methods():
#do sth. with Methods
我尝试使用 ast
模块:
with open(basename(__file__), "rb") as f:
g = ast.parse(f.read(), basename(__file__))
for e in g.body:
if isinstance(e, ast.AsyncFuntionDef):
method_list.append(e)
这可能会找到所有协程,但我无法提取任何对它的引用。
我也试过,
method_list = inspect.getmembers(basename(__file__), inspect.iscoroutinefunction))
但这也找不到任何东西。
所以我找到了一种方法来找到当前文件本身的Coroutines:
my_module_coros = inspect.getmembers(modules[__name__]), inspect.iscoroutinefunction)
coro_list = [coro[1] for coro in my_module_coros if (inspect.getmodule(coro[1]) == modules[__name__]) and coro[0] != "main"]
这将 return 协程列表,没有 main 本身。
我想获取当前文件中所有协程的列表(extern_method 和 extern_method2 在我的代码示例中)。行为应与:method_list = [extern_method, extern_method2]
相同,但我希望它自动列出。
我有这样的文件结构:
@wraps(lambda: extern_method)
@my_decorator
async def extern_method(arg)
return arg + "hello"
@wraps(lambda: extern_method2)
@my_decorator
async def extern_method2(arg)
return arg + 123
class myclass:
(...)
def find_extern_methods():
#here missing code
return method_list
(...)
def do_sth_with_methods():
#do sth. with Methods
我尝试使用 ast
模块:
with open(basename(__file__), "rb") as f:
g = ast.parse(f.read(), basename(__file__))
for e in g.body:
if isinstance(e, ast.AsyncFuntionDef):
method_list.append(e)
这可能会找到所有协程,但我无法提取任何对它的引用。
我也试过,
method_list = inspect.getmembers(basename(__file__), inspect.iscoroutinefunction))
但这也找不到任何东西。
所以我找到了一种方法来找到当前文件本身的Coroutines:
my_module_coros = inspect.getmembers(modules[__name__]), inspect.iscoroutinefunction)
coro_list = [coro[1] for coro in my_module_coros if (inspect.getmodule(coro[1]) == modules[__name__]) and coro[0] != "main"]
这将 return 协程列表,没有 main 本身。