<分区>
在 C# 程序中,我想检查给定的 Python 文件以了解它提供的功能。如果可能,我还想获得有关每个函数和参数的元信息,例如描述。
我可以控制 C# 端和 Python 端。
我怎样才能做到这一点?
(至于用例:我将在 Python 中编写一个调度程序函数,C# 程序可以在 python 脚本中调用它来执行特定的函数,给定所需的参数。)
<分区>
在 C# 程序中,我想检查给定的 Python 文件以了解它提供的功能。如果可能,我还想获得有关每个函数和参数的元信息,例如描述。
我可以控制 C# 端和 Python 端。
我怎样才能做到这一点?
(至于用例:我将在 Python 中编写一个调度程序函数,C# 程序可以在 python 脚本中调用它来执行特定的函数,给定所需的参数。)
最佳答案
没试过。但是认为您可以使用模块 optparse
的组合(取自 How do I get list of methods in a Python class? ):
from optparse import OptionParser
import inspect
inspect.getmembers(OptionParser, predicate=inspect.ismethod)
使用function.__doc__
从方法中获取文档
def factorial(x):
'''int f(int x); returns the factorial of an integer number'''
#code here
>>> factorial.__doc__
'int f(int x); returns the factorial of an integer number'
使用第一部分 (int f(int x);
) 作为它需要和返回的参数的描述(你可以把这部分只拿字符串直到第一个分号)
然后使用 getattr
调用函数 ( https://docs.python.org/2/library/functions.html#getattr ):
getattr(myObject, 'factorial', '3')()
希望对你有帮助
关于C#:python 文件中的类反射机制(获取函数、参数等),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33567732/