与ruby代码交互时,从stdin读取Python将挂起
我试图将python和ruby代码放到对话中,我从这个链接()中找到了方法 我尝试了最后一种方法,使用stdin和stdout传递信息。我对源代码做了一些修改,使之适合Python3.4,但我不确定我修改的代码是否把所有事情都弄糟了。我的python程序在读取stdin时总是挂起,并且没有打印任何内容。我不熟悉stdin和stdout,所以我只是想知道为什么这不起作用 以下是我的ruby代码:与ruby代码交互时,从stdin读取Python将挂起,python,ruby,encoding,stdio,Python,Ruby,Encoding,Stdio,我试图将python和ruby代码放到对话中,我从这个链接()中找到了方法 我尝试了最后一种方法,使用stdin和stdout传递信息。我对源代码做了一些修改,使之适合Python3.4,但我不确定我修改的代码是否把所有事情都弄糟了。我的python程序在读取stdin时总是挂起,并且没有打印任何内容。我不熟悉stdin和stdout,所以我只是想知道为什么这不起作用 以下是我的ruby代码: $stdin.set_encoding("utf-8:utf-8") $stdout.set_enco
$stdin.set_encoding("utf-8:utf-8")
$stdout.set_encoding("utf-8:utf-8")
while cmd = $stdin.gets
cmd.chop!
if cmd == "exit"
break
else
puts eval(cmd)
puts "[end]"
$stdout.flush
end
end
我不确定是否可以这样设置内部编码和外部编码。下面是我的python代码:
from subprocess import Popen, PIPE, STDOUT
print("Launch slave process...")
slave = Popen(['ruby', 'slave.rb'], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
while True:
line = input("Enter expression or exit:")
slave.stdin.write((line+'\n').encode('UTF-8'))
result = []
while True:
if slave.poll() is not None:
print("Slave has terminated.")
exit()
line = slave.stdout.readline().decode('UTF-8').rstrip()
if line == "[end]":
break
result.append(line)
print("result:")
print("\n".join(result))
当我尝试运行python脚本时,输入“3*4”,然后按enter键,直到我使用退出代码1和KeyboardInterrupt Exception手动中断进程,才显示任何内容。
我已经为这个问题挣扎了很长时间,我不知道出了什么问题。。。
提前感谢您提供的任何潜在帮助 不同之处在于,在Python 3.4中默认情况下,
bufsize=-1
,因此slave.stdin.write()
不会立即将行发送到ruby
子进程。快速修复方法是添加slave.stdin.flush()
调用
#!/usr/bin/env python3
from subprocess import Popen, PIPE
log = print
log("Launch slave process...")
with Popen(['ruby', 'slave.rb'], stdin=PIPE, stdout=PIPE,
bufsize=1, universal_newlines=True) as ruby:
while True:
line = input("Enter expression or exit:")
# send request
print(line, file=ruby.stdin, flush=True)
# read reply
result = []
for line in ruby.stdout:
line = line.rstrip('\n')
if line == "[end]":
break
result.append(line)
else: # no break, EOF
log("Slave has terminated.")
break
log("result:" + "\n".join(result))
它使用universal\u newlines=True
启用文本模式。它使用locale.getpreferredencoding(False)
对字节进行解码。如果您想强制执行utf-8
编码,而不考虑区域设置,则删除universal\u新行
,并将管道包装到io.TextIOWrapper(encoding=“utf-8”)
()