微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Linux 中 Python 子进程之间的管道难点

如何解决Linux 中 Python 子进程之间的管道难点

以下脚本(应该从 p1 获取输出并将其通过管道传输到 p2,然后在终端中输出结果)似乎没有按预期工作。

代码如下:

#!/binr/bin/python
# Script to lauch mosquitto_sub to monitor a mqtt topic -- Syntax : mosk topic
import sys
import subprocess

total = len(sys.argv)
cmdargs = str(sys.argv)
print ("The total numbers of args passed to the script: %d " % total)
print ("Args list: %s " % cmdargs)
# Pharsing args one by one 
print ("Script name: %s" % str(sys.argv[0]))
print ("First argument: %s" % str(sys.argv[1]))


path = str(sys.argv[1])
print (path)


p1 = subprocess.Popen(['mosquitto_sub','-h','192.168.1.100','-t',path,'-v'],shell=False,stdout=subprocess.PIPE)
p2 = subprocess.Popen(['ts'],stdin=p1.stdout,stdout=subprocess.PIPE)

for line in p2.stdout:
    sys.stdout.write(line)

输入如下“./mosk2.py test/+”,在通过 mosquitto 发布相关主题的 MQTT 时,我从未在终端中得到预期的输出

解决方法

已解决 - 我最终巧妙地解决了问题(作弊),如下所示:

cmd = "mosquitto_sub -h 192.168.1.100 -v -t " + topic + " | ts"
print "The command which was executed is : ",cmd

def run_command(command):
    process = subprocess.Popen(command,stdout=subprocess.PIPE,shell=True)
    while True:
        output = process.stdout.readline()
        if output == '' and process.poll() is not None:
            break
        if output:
            print output.strip()
    rc = process.poll()
    return rc

run_command(cmd) #This is the lauch of the actual command

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。