Linux中Python子进程之间管道的困难
Posted
技术标签:
【中文标题】Linux中Python子进程之间管道的困难【英文标题】:Difficulties in pipes between Python subprocesses in Linux 【发布时间】:2021-03-30 17:35:51 【问题描述】:以下脚本(应该从 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, shell=False, stdout=subprocess.PIPE)
for line in p2.stdout:
sys.stdout.write(line)
输入如下“./mosk2.py test/+”,并在通过 mosquitto 发布相关主题的 MQTT 时,我从未在终端中获得预期的输出
【问题讨论】:
【参考方案1】:已解决 - 我最终巧妙地解决了问题(作弊),如下所示:
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
【讨论】:
以上是关于Linux中Python子进程之间管道的困难的主要内容,如果未能解决你的问题,请参考以下文章