我使用Twisted完成了它,因为它提供了比轮询更好的抽象。基本上,您需要首先定义 Python 和 Haskell 程序如何相互通信的方式(在 Twisted 中称为协议),例如,数据包有多长,如何处理错误等。然后您只需将它们编码。
这是haskell代码:
-- File "./Hs.hs"
import Control.Concurrent
import System.IO
main = do
-- Important
hSetBuffering stdout NoBuffering
-- Read a line
line <- getLine
-- parse the line and add one and print it back
putStrLn (show (read line + 1))
-- Emphasize the importance of hSetBuffering :P
threadDelay 10000000
这是Python代码:
# File "./pyrun.py"
import os
here = os.path.dirname(os.path.abspath(__file__))
from twisted.internet import tksupport, reactor, protocol
from twisted.protocols.basic import LineReceiver
from Tkinter import Tk, Label, Entry, StringVar
# Protocol to handle the actual communication
class HsProtocol(protocol.ProcessProtocol):
def __init__(self, text):
self.text = text
def connectionMade(self):
# When haskell prog is opened
towrite = self.text + '\n'
# Write a line to the haskell side
self.transport.write(towrite)
def outReceived(self, data):
# When haskell prog write something to the stdout
# Change the label in the tk window to be the received data
label_var.set(data[:-1])
def send_num_to_hs(_event):
content = enternum.get()
# The abspath of the haskell program
prog = os.path.join(here, 'Hs')
reactor.spawnProcess(HsProtocol(content), # communication protocol to use
prog, # path
[prog] # args to the prog
)
# Setting up tk
root = Tk()
# On main window close, stop the tk reactor
root.protocol('WM_DELETE_WINDOW', reactor.stop)
# Since I'm going to change that label..
label_var = StringVar(root, 'Enter a number')
# Label whose content will be changed
label = Label(root, textvariable=label_var)
label.pack()
# Input box
enternum = Entry(root)
enternum.pack()
enternum.bind('<Return>', send_num_to_hs)
# Patch the twisted reactor
tksupport.install(root)
# Start tk's (and twisted's) mainloop
reactor.run()