C#:类似反射的机制进入 python 文件(获取函数、参数等)
C#: reflection-like mechanism into python file (get functions, parameters etc)
我想在 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);
) 作为它需要的参数的描述和 returns (你可以把这部分只拿字符串直到第一个分号)
并使用getattr
调用函数(https://docs.python.org/2/library/functions.html#getattr):
getattr(myObject, 'factorial', '3')()
希望对您有所帮助
我想在 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);
) 作为它需要的参数的描述和 returns (你可以把这部分只拿字符串直到第一个分号)
并使用getattr
调用函数(https://docs.python.org/2/library/functions.html#getattr):
getattr(myObject, 'factorial', '3')()
希望对您有所帮助