Haskell库的Python接口

2024-10-03 15:24:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要一个到Haskell库的Python接口。该库使用非标准/用户创建的类型,因此它们不能绑定到C类型,因此我不确定FFI是否可以工作

到目前为止,我的尝试包括将GHCI作为子流程运行,然后将代码作为输入传递并解析输出:

# my current setup
from subprocess import Popen, PIPE, STDOUT
proc = Popen(["ghci", "some_haskel_file.hs"], stdin=PIPE, stdout=PIPE, stderr=STDOUT)

# clear initial output of GHCI
for _ in range(7): proc.stdout.readline()

# this next part may be repeated multiple times
proc.stdin.write(some_haskell_code)
proc.stdin.flush()
output = proc.stdout.readline()

我希望output同时包含输出和任何错误消息。但我无法让我的代码可靠地从GHCI获得输出

下面是.readline方法阻塞的示例,即使已给出输入:


>>> from subprocess import Popen, PIPE, STDOUT
>>> proc = Popen(["ghci", "Session.hs"], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
>>> for _ in range(7): proc.stdout.readline()
...
b'GHCi, version 8.6.3: http://www.haskell.org/ghc/  :? for help\r\n'
b'[1 of 5] Compiling Classes          ( Classes.hs, interpreted )\r\n'
b'[2 of 5] Compiling Functions        ( Functions.hs, interpreted )\r\n'
b'[3 of 5] Compiling Rule             ( Rule.hs, interpreted )\r\n'
b'[4 of 5] Compiling Graph            ( Graph.hs, interpreted )\r\n'
b'[5 of 5] Compiling Main             ( Session.hs, interpreted )\r\n'
b'Ok, five modules loaded.\r\n'
>>> proc.stdin.write("completeGraph 3".encode('utf-8'))
15
>>> proc.stdin.flush()
>>> output = proc.stdout.readline()
|

此外,GHCI在将提示符*Main>发送到stdout之前需要输入,因为以下情况是阻塞的:

>>> from subprocess import Popen, PIPE, STDOUT
>>> proc = Popen(["ghci", "Session.hs"], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
>>> for _ in range(8): proc.stdout.readline()
...
b'GHCi, version 8.6.3: http://www.haskell.org/ghc/  :? for help\r\n'
b'[1 of 5] Compiling Classes          ( Classes.hs, interpreted )\r\n'
b'[2 of 5] Compiling Functions        ( Functions.hs, interpreted )\r\n'
b'[3 of 5] Compiling Rule             ( Rule.hs, interpreted )\r\n'
b'[4 of 5] Compiling Graph            ( Graph.hs, interpreted )\r\n'
b'[5 of 5] Compiling Main             ( Session.hs, interpreted )\r\n'
b'Ok, five modules loaded.\r\n'
|

还有其他更成功的方法吗


Tags: offoroutputreadlinesessionstdinstdoutproc
1条回答
网友
1楼 · 发布于 2024-10-03 15:24:08

通过GHCI的管道似乎极为脆弱。如果该库的API目前不适用于FFI,我建议编写另一个(Haskell)库来封装它,并提供更适合您的API。然后通过Python的FFI调用它,而不是通过GHCI管道。在文本中来回浏览永远不会有多大乐趣

相关问题 更多 >