在python中控制ruby程序的stdin和stdout

在python中控制ruby程序的stdin和stdout,python,ruby,python-2.7,python-3.x,six-python,Python,Ruby,Python 2.7,Python 3.x,Six Python,首先我应该注意到:我是一个python程序员,对ruby一无所知 现在,我需要为ruby程序的stdin提供数据,并使用 python程序。 我尝试了(forth解决方案),代码在python2.7中工作,但在python3中不工作;python3代码读取输入而不输出 现在,我需要一种方法将ruby程序绑定到Python2或Python3 我的尝试: 这段代码用六个模块编写,具有跨版本兼容性 python代码: from subprocess import Popen, PIPE as pip

首先我应该注意到:我是一个python程序员,对ruby一无所知

现在,我需要为ruby程序的stdin提供数据,并使用 python程序。
我尝试了(forth解决方案),代码在python2.7中工作,但在python3中不工作;python3代码读取输入而不输出

现在,我需要一种方法将ruby程序绑定到Python2或Python3

我的尝试: 这段代码用六个模块编写,具有跨版本兼容性

  • python代码:

    from subprocess import Popen, PIPE as pipe, STDOUT as out
    
    import six
    
    print('launching slave')
    slave = Popen(['ruby', 'slave.rb'], stdin=pipe, stdout=pipe, stderr=out)
    
    while True:
        if six.PY3:
            from sys import stderr
            line = input('enter command: ') + '\n'
            line = line.encode('ascii')
        else:
            line = raw_input('entercommand: ') + '\n'
        slave.stdin.write(line)
        res = []
        while True:
            if slave.poll() is not None:
                print('slave rerminated')
                exit()
            line = slave.stdout.readline().decode().rstrip()
            print('line:', line)
            if line == '[exit]': break
            res.append(line)
        print('results:')
        print('\n'.join(res))
    
  • ruby代码:

    while cmd = STDIN.gets
        cmd.chop!
        if cmd == "exit"
            break
        else
            print eval(cmd), "\n"
            print "[exit]\n"
            STDOUT.flush
        end
    end
    
注: 欢迎任何一种做这件事的方法!(如套接字编程等)

另外,我认为最好不要使用管道作为标准输出,而是使用类似文件的对象。(如
tempfile
StringIO
等)

这是因为
bufsize
。在Python2.x中,默认值为0(未缓冲)。在Python3.x中,它改为
-1
(使用系统的默认缓冲区大小)

明确指定它将解决您的问题

slave = Popen(['ruby', 'slave.rb'], stdin=pipe, stdout=pipe, stderr=out, bufsize=0)