2

From a C# program, I want to examine a given python file for the functions it offers. If possible, I also want to get metainformation about each function and parameter, like a description.

I can control both the C# side and the Python side.

How can I achieve that?

(As for the use case: I am going to write a dispatcher function in Python that the C# program can call inside the python script to execute a specific function, given the required arguments.)

Andreas Reiff
  • 7,961
  • 10
  • 50
  • 104

1 Answers1

1

Never tried this. But think you could use a combination of the module optparse (Taken from How do I get list of methods in a Python class?):

from optparse import OptionParser
import inspect
inspect.getmembers(OptionParser, predicate=inspect.ismethod)

With function.__doc__ to get the documentation from the method like

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'

Use the first part (int f(int x);) as the description of what parameters it needs and returns (You could take this part just taking the string until first semicolon)

And use getattr to call the function (https://docs.python.org/2/library/functions.html#getattr):

getattr(myObject, 'factorial', '3')()

Hope this helps you

Community
  • 1
  • 1
Mr. E
  • 2,070
  • 11
  • 23
  • Thank you. I would like to do this from the C# side though, not python-to-python. – Andreas Reiff Nov 06 '15 at 14:25
  • 1
    Well in your C# code should have some code like `getFunctions()` which will call the `optparser` in your python code, then it will return the corresponding part of the `__doc__` string to the C# process do what you need and then use something like `callFunction(args)` which will call `getattr` in python process. If i undestood you right that's what you want – Mr. E Nov 06 '15 at 14:51
  • 1
    Yes, that also fulfuills my requirements. Coming from the C# side, I would prefer the logic there, but this is also fine. (Plus, in this case I would have to call into the Python code already when examining it, in the other case I only have to do that at runtime. Those are 2 different scenarios in my case.) – Andreas Reiff Nov 06 '15 at 14:59
  • 1
    I think you could open python file as text from C# code and look for the triple-quoted string or just look for the `def func(param)` (Lines starting with "def"), but I don't think it's scalable neither a good practice – Mr. E Nov 06 '15 at 15:06