扭曲的spawnProcess,将一个进程的输出发送到另一个进程的输入

2023-12-25

我正在尝试使用扭曲的spawnProcess来复制类似这样的行为:

cat <input.txt | wc -w

这只是两个命令的示例,实际上我有自己的进程(例如 python 或 bash 脚本或外部程序),其中每个进程从 stdin 读取并写入 stdout。就像上面的示例一样,我想将标准输出从一个进程传输到另一个进程的标准输入,并且我想使用spawnProcess 来完成此操作。我在这里使用了一些提示:

用spawnProcess扭曲管道两个进程 https://stackoverflow.com/questions/23012265/twisted-pipe-two-processes-with-spawnprocess

但我无法让它发挥作用。当从第二个spawnProcess协议上的标准输入读取时,它只是挂起。我的代码如下。我做错了什么?我究竟怎样才能实现这个目标?从第一个spawnProcess中调用第二个spawnProcess是否更好?

#!/usr/bin/env python

from twisted.internet import protocol
from twisted.internet import reactor
import re
import os
import sys

class CatPP(protocol.ProcessProtocol):
    def __init__(self,input_data):
        self.input_data=input_data
        self.data = ""

    def connectionMade(self):
        print "connectionMade in CatPP! Now writing to stdin of cat"
        print "   writing this data: %s" % self.input_data
        self.transport.write(self.input_data+'\n')
        print "   closing stdin"
        self.transport.closeStdin() # tell them we're done
        print "   stdin closed"

    def outReceived(self, data):
        print "outReceived from cat! with %d bytes!" % len(data)
        self.data = self.data + data
        print "    received this: %s" % self.data

    def errReceived(self, data):
        print "errReceived from cat! with %d bytes!" % len(data)

    def inConnectionLost(self):
        print "inConnectionLost for cat! stdin is closed! (we probably did it)"

    def outConnectionLost(self):
        print "outConnectionLost for cat! The child closed their stdout!"
        # now is the time to examine what they wrote
        print "I saw cat write this:", self.data

    def errConnectionLost(self):
        print "errConnectionLost for cat! The child closed their stderr."

    def processExited(self, reason):
        print "processExited for cat, status %d" % (reason.value.exitCode,)

    def processEnded(self, reason):
        print "processEnded for cat, status %d" % (reason.value.exitCode,)

class WcPP(protocol.ProcessProtocol):
    def __init__(self):
        self.data = ""

    def connectionMade(self):
        print "connectionMade! Now reading from pipe to get stdin for wp"
        print "    reading from stdin"
        txt = sys.stdin.read()
        print "  Read this from stdin: %s" % (txt,)
        self.transport.write(txt)
        self.transport.closeStdin() # tell them we're done

    def outReceived(self, data):
        print "outReceived from cat! with %d bytes!" % len(data)
        self.data = self.data + data

    def errReceived(self, data):
        print "errReceived from cat! with %d bytes!" % len(data)

    def inConnectionLost(self):
        print "inConnectionLost for cat! stdin is closed! (we probably did it)"

    def outConnectionLost(self):
        print "outConnectionLost for cat! The child closed their stdout!"
        # now is the time to examine what they wrote
        print "Final output:", self.data
        #(dummy, lines, words, chars, file) = re.split(r'\s+', self.data)
        #print "I saw %s lines" % lines

    def errConnectionLost(self):
        print "errConnectionLost for cat! The child closed their stderr."

    def processExited(self, reason):
        print "processExited for cat, status %d" % (reason.value.exitCode,)

    def processEnded(self, reason):
        print "processEnded for cat, status %d" % (reason.value.exitCode,)
        reactor.stop()

readPipe, writePipe = os.pipe()

handle=open('junkin.txt','r')
cat_txt=handle.read()
handle.close()

pp1 = CatPP(cat_txt)
pp2 = WcPP()
reactor.spawnProcess(pp1, "cat", ["cat"], {}, childFDs={1: writePipe})
reactor.spawnProcess(pp2, "wc", ["wc", "-w"], {},childFDs={0: readPipe})
reactor.run()
try:
    os.close(readPipe)
except:
    print "Exception closing readPipe"
try:
    os.close(writePipe)
except:
    print "Exception closing writePipe"

这是一个工作示例。

配管通过时cat | wc, spawnProcess重复管道,因此您需要关闭它们。

from twisted.internet import protocol
from twisted.internet import reactor
import os

class Writer(protocol.ProcessProtocol):
  def __init__(self, data):
    self.data = data
  def connectionMade(self):
    print "Writer -- connection made"
    self.transport.writeToChild(0, self.data)
    self.transport.closeChildFD(0)
  def childDataReceived(self, fd, data):
    pass
  def processEnded(self, status):
    pass

class Reader(protocol.ProcessProtocol):
  def __init__(self):
    pass
  def connectionMade(self):
    print "Reader -- connection made"
    pass
  def childDataReceived(self, fd, data):
    print "Reader -- childDataReceived"
    self.received = data
  def processEnded(self, status):
    print "process ended, got:", self.received

class WriteRead(protocol.ProcessProtocol):
  def __init__(self, data):
    self.data = data
  def connectionMade(self):
    self.transport.writeToChild(0, self.data)
    self.transport.closeChildFD(0)
  def childDataReceived(self, fd, data):
    self.received = data
    print "got data:", data
  def processEnded(self, status):
    print "process ended - now what?"

def test1(data):
    # just call wc
    p2 = reactor.spawnProcess(WriteRead(data), "wc", ["wc"], env=None, childFDs={0: "w", 1: "r"})
    reactor.run()

def test2(data):
    rfd, wfd = os.pipe()
    p1 = reactor.spawnProcess(Writer(data), "cat", ["cat"], env=None, childFDs={0:"w", 1: wfd })
    p2 = reactor.spawnProcess(Reader(),     "wc", ["wc", "-w"], env=None, childFDs={0: rfd, 1: "r"})
    os.close(rfd)
    os.close(wfd)
    reactor.run()

test2("this is a test")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

扭曲的spawnProcess,将一个进程的输出发送到另一个进程的输入 的相关文章

随机推荐

  • 从现有 MySQL 数据库逆向工程 SQLAlchemy 声明类定义?

    我有一个预先存在的 mysql 数据库 其中包含大约 50 个表 而不是手动编写声明式风格的 SqlAlchemy 类 如图所示 http www sqlalchemy org docs 05 ormtutorial html creati
  • JavaScript 中不接受早于 13 个月的起始日期

    这里我有 从日期 和 到日期 以及提交按钮 我在这个项目中使用 Telerik radate 控制 所以 我无法添加 Telerik 控件 这里一切都很好满足我的要求 并且有一个增强功能 http jsfiddle net ssthil 4
  • 什么是 Microsoft SharePoint? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • C++ 中的哈希表?

    每当我需要存储与特定类型的值 键值 例如字符串或其他对象 关联的一些数据时 我通常使用 C stdlib 映射 stdlib 映射实现基于树 它比标准数组或 stdlib 向量提供更好的性能 O log n 我的问题是 您是否知道任何可以提
  • 提示的键盘快捷键

    通常 当我选择一个提示 例如重构我所在的某一行 时 当左侧显示紫色提示图标或灯泡图标时 我单击它 然后选择我想要的重构 我不想用我的鼠标 我如何打开左侧的对话框 resharper 会不显眼地向您显示左侧的任何对话框 只是想找到一种比使用鼠
  • 限制每个 Apache 虚拟主机的带宽 [关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 我将启动一个 2GB Linode VPS 来托管几个 Wordpress CMS 站点和一个基于 Yii 框架的站点 我计划使用 Apache 虚拟
  • 将“onclick”处理程序添加到纯 JavaScript 中动态创建的元素

    我正在页面上动态创建和删除元素 a 和 button 我想在创建它们时向它们添加处理程序 onclick 到目前为止我见过的所有例子都是jquery 的 我怎样才能用纯 JavaScript 做到这一点 你可以这样做 for var i 0
  • 当用户关闭其中一个窗口时,WPF 关闭所有窗口

    有一个具有多个窗口的 WPF 应用程序 最初只有一个窗口 用户可以转到下一个窗口 同时隐藏上一个窗口 当他们回来时 隐藏的窗口再次出现 问题是 当用户关闭某些窗口时 隐藏的窗口继续作为进程运行 当用户关闭任何一个时 是否可以关闭所有它们 如
  • 在组件外部使用 VueI18n 的问题

    我正在尝试在组件外部使用 i18n 我找到了这个解决方案https github com dkfbasel vuex i18n issues 16 https github com dkfbasel vuex i18n issues 16告
  • 使用张量流数据集利用 GPU

    在数据训练期间 我的 GPU 利用率约为 40 并且我清楚地看到基于 TensorFlow Profiler 的数据复制操作占用了大量时间 参见附图 我认为 MEMCPYHtoD 选项正在将批次从 CPU 复制到 GPU 并阻止使用 GPU
  • 有没有办法将语法与 HTML 5 语音输入 API 结合使用?

    我正在使用 HTML 5 语音输入 API 我想让服务器知道它可以期望从语音输入返回哪些答案 有没有办法设置可能的输入列表 在 Google Chrome 中 您还不能使用语法 总的来说 他们决定仅使用自由形式识别 相关问题是Google
  • 在addListener中传递google事件数据

    我有可变数量的文本字段 我正在动态初始化 Google 地图自动完成功能 问题是每次地点已更改事件被触发 我需要确切地知道它是在哪个输入框上触发的 我怎样才能将这些数据传递给我的保存位置功能 现在 event评估结果为未定义 initAut
  • 是否有与

    HTML 中是否有一个标签只有在启用 JavaScript 时才会显示其内容 我知道
  • Svelte 框架:环境变量未出现在 svelte 应用程序中

    我正在尝试在我的 svelte 应用程序中使用环境变量 我已经安装了 Rollup plugin replace and dotenv 我创建了一个 env文件来保存我的API KEY并将以下内容添加到plugins in rollup c
  • 在惯用的 Rust 中,嵌套匹配是一种不好的做法吗?

    我有一个get url content函数并且不关心错误 这只是一个测试 它返回一个Option
  • 电子邮件验证是否需要域部分包含一个点?

    我注意到内置的浏览器验证
  • jQuery 单击不适用于新的无限滚动元素

    在我的页面上 我有一个包含项目的列表 您可以单击 查看更多 按钮 该按钮会显示有关此主题的更多信息 这个点击函数是在另一个页面的 jQuery 中的 我在此页面上实现了无限滚动器 但现在 查看更多 按钮不适用于新元素 仅适用于第一个元素 仅
  • 如何仅比较一个月和一年而不是完整的日期?

    我需要编写一个存储过程以允许某人搜索数据库 然而 我得到的只是月份和年份的整数 数据库有月份和年份字段 但我不知道如何进行比较 例如 我得到 2008 年 3 月和 2010 年 6 月 我需要在数据库中搜索日期 由月份和年份字段指定 介于
  • Django {% if forloop.first %} 问题

    我的模板中有以下代码 for object in object list with game object game for category in object game objectmeta categories all if cate
  • 扭曲的spawnProcess,将一个进程的输出发送到另一个进程的输入

    我正在尝试使用扭曲的spawnProcess来复制类似这样的行为 cat