I am trying to call a python function from F#. So far, I managed to call a simple Python function (eg: to print a string). The problem is that I can't manage to pass a F# method to my Python function and call it from here.
Program.fs
let printMsg () = Console.WriteLine "Print from F#"
[<EntryPoint>]
let main argv =
Environment.SetEnvironmentVariable ("PATH", pythonPath + Environment.GetEnvironmentVariable "PATH")
PythonEngine.Initialize ()
let import = PythonEngine.ImportModule "HelloWorld"
let helloWorld = import?HelloWorld()
helloWorld?exec(printMsg)
PythonEngine.Shutdown ()
0
Helloworld.py
class HelloWorld:
def __init__(self):
print("__init__")
def exec(self, printMsg):
printMsg()
But I get Python.Runtime.PythonException: 'TypeError: object is not callable'
on the helloWorld?exec(printMsg)
line of Program.fs
, caused by the call to printMsg()
from Python.
You need to construct a delegate from your F# function, then pass it to Python. I think System.Action(printMsg)
should suffice.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.