python - 在Python中同时读取stdin并写入stdout

标签 python subprocess

我是线程新手,所以我觉得好像错过了一个明显的点,但我找不到与该主题相关的先前问题。

我想制作一个写入标准输入并读取 C 程序的标准输出的程序。这是主程序中的代码。

from subprocess import Popen, PIPE
from threading import Thread
from Queue import Queue, Empty
from os import getcwd
import time
import random

chatter = Queue(maxsize=10)  # Queue of strings to be sent to the program


class Chatter():
    def stream_talker(self, identifier, stream):
        while True:
            if not chatter.empty():
                self.proc.stdin.write(chatter.get(True, 1))

    def stream_watcher(self, identifier, stream):
        while True:
            for line in stream:
                print line

    def main(self):
        self.proc = Popen(getcwd() + '/main', stdout=PIPE, stdin=PIPE)
        Thread(target=self.stream_talker, name='stdin-talker', args=('STDIN', self.proc.stdin)).start()
        Thread(target=self.stream_watcher, name='stdout-listening', args=('STDOUT', self.proc.stdout)).start()

        while True:
            chat = raw_input('Enter chatter: ')
            if len(chat) > 0:
                chatter.put(chat)


if __name__ == '__main__':
    chatt = Chatter()
    chatt.main()

这是它调用的 main.c 程序。

#include <stdio.h>
#include <stdlib.h>

int main(){
  while (1){
    int bytes_read;
    size_t nbytes = 100;
    char *my_string;

    my_string = (char *)malloc(nbytes + 1);
    bytes_read = getline (&my_string, &nbytes, stdin);

    if (bytes_read == -1)
    {
      puts ("ERROR!");
    }
    else{
      puts (my_string);
    }
    free(my_string);
  }

  return 0;

}

当前的问题是,虽然它将运行,但 stdout 永远不会打印。

最佳答案

看起来您的主要问题是调用了两个 stream_talker() 而没有调用 stream_watcher()

此外,您可能不想在队列上忙等待(因为这违背了使用队列的全部意义)。您的代码会尽可能快地轮询chatter.empty(),直到队列中有内容为止。直接使用chatter.get()来代替;它会阻塞,直到有可用的东西或直到超时。

最后,如果您写入 stream_talker() 中的 stream 参数,而不是硬编码 self.proc.stdin,您可能会在以后避免一些困惑。

关于python - 在Python中同时读取stdin并写入stdout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28460338/

相关文章:

python - TensorFlow 用户应该更喜欢 SavedModel 而不是 Checkpoint 或 GraphDef?

python - 子进程,从 STDOUT 读取时重复写入 STDIN (Windows)

python - 从 python 调用 BCP 抛出超时异常,然后立即完成

python - 从 python 中杀死一个子进程,包括它的子进程

python - 通过rpy2从ggplot2中的geom_histogram中删除基线?

Python:如何按位将 4 位数字的数组转换为更大的数字?

android - Android 上的 kivy/Python 缺少 Unicode 编解码器?

python - 在subprocess.Popen中,bufsize适用于哪个文件?

.net - 当通过 C# 的 Process 类产生时,处理标准错误和程序输出的正确方法?

python - 使用 beautifulsoup 将大型 xml 文件拆分为多个文件