首页 > 解决方案 > Python和Ruby之间的管道

问题描述

我正在编写一个代码,它可以使用“管道”在 Python 和 Ruby 脚本之间发送数据,但无法让它工作。有什么建议或替代方法吗?

我已经编写了简单的脚本来让它工作并建立在它们之上。目标是将“管道”功能集成到项目中。在项目中,Python 脚本是向 Ruby 脚本发送一个 .txt 文件,Ruby 脚本将提取参数值并存储在各自的数组中。然后我想将数组发送回 Python 脚本。

到目前为止,我制作的简单脚本的灵感来自https://www.decalage.info/python/ruby_bridge。运行时,它会不停地继续,不会产生任何结果。目标是将整数 6 发送到添加了 5 的 Ruby 脚本,并将总和发送回 Python 脚本。使用 ctrl + c 中止时,编写如下:

File "./com_ruby.py", line 33, in <module>
    sss = slave.stdout.readline().rstrip()

我的 Python 脚本:

from subprocess import Popen, PIPE, STDOUT

print('launching slave process...')
slave = Popen(['ruby', 'provar.rb'], stdin=PIPE, stdout=PIPE, stderr=STDOUT)

while True:

    num = bytes([6])
    slave.stdin.write(num)
    # result will be a list of lines:
    result = []
    # read slave output line by line, until we reach "[end]"
    while True:
        # check if slave has terminated:
        if slave.poll() is not None:
            print('slave has terminated.')
            exit()
        # read one line, remove newline chars and trailing spaces:
        sss = slave.stdout.readline().rstrip()
        print('line: ', sss)
        if sss == '[end]':
            break
        result.append(sss)
    print('result:')
    print('\n'.join(result))

我的 Ruby 脚本:

while cmd = STDIN.gets

    cmd.chop!

    cmd = cmd + 5

    cmd.to_s
    print eval(cmd),"\n"
    # append [end] so that master knows it's the last line:
    print "[end]\n"
    # flush stdout to avoid buffering issues:
    STDOUT.flush

end

有没有更好但更简单的方法来在两个脚本之间进行数据“管道”?

标签: pythonrubypython-3.xpipe

解决方案


推荐阅读