有没有办法将 F# 方法传递给 Python 函数?
Is there a way to pass a F# method to a Python function?
我正在尝试从 F# 调用 python 函数。到目前为止,我设法调用了一个简单的 Python 函数(例如:打印一个字符串)。问题是我无法设法将 F# 方法传递给我的 Python 函数并从此处调用它。
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()
但我在 Program.fs
的 helloWorld?exec(printMsg)
行得到 Python.Runtime.PythonException: 'TypeError : object is not callable'
,这是由于 Python 对 printMsg()
的调用造成的。
您需要从 F# 函数构造一个委托,然后将其传递给 Python。我觉得 System.Action(printMsg)
应该够了。
我正在尝试从 F# 调用 python 函数。到目前为止,我设法调用了一个简单的 Python 函数(例如:打印一个字符串)。问题是我无法设法将 F# 方法传递给我的 Python 函数并从此处调用它。
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()
但我在 Program.fs
的 helloWorld?exec(printMsg)
行得到 Python.Runtime.PythonException: 'TypeError : object is not callable'
,这是由于 Python 对 printMsg()
的调用造成的。
您需要从 F# 函数构造一个委托,然后将其传递给 Python。我觉得 System.Action(printMsg)
应该够了。