如何解决Python3 和 subprocess.Popen,写入标准输入似乎不起作用
我想弄清楚如何在 raspberry pi 上使用管道启动子进程,并在 stdin 上输入它并检查 stdout 的输出。我写了一个简单的 shell 脚本来回显一些东西,这样我就可以看看我是否可以捕获输出。脚本循环直到它看到只有“q”的输入,然后退出。我需要能够在子进程运行期间多次发送单个字符或 \n 终止的字符串,并捕获子进程的输出。
我在 stdout 管道上看到第一行输出,但在写入 stdin 后,它挂在 stdout 的 readline 上。这向我表明,stdin 写入未到达子进程。
我已经尝试了 subprocess.communicate 和其他一些更复杂的建议,但我无法将数据发送到子进程上的 stdin。下面是我编写的简单代码来测试它,以便我可以了解有关 subprocess 模块的更多信息。 任何帮助将不胜感激。
# -------- simple bash script to echo stdin to stdout and terminate on "q" -------
#!/bin/bash
echo "Hello there"
ans=""
while ! [ "$ans" == "q" ]; do
read ans
echo "Input was $ans"
done
echo "all done"
# --------- python test program ----------
#!/usr/bin/env python3
from subprocess import Popen,PIPE,STDOUT
p = Popen(['./tst_read.sh'],stdout=PIPE,stdin=PIPE,stderr=STDOUT)
print("Popen,pid:",p.pid)
print(p.stdout.readline().decode())
p.stdin.write(b'some stuff\n')
print(p.stdout.readline().decode())
p.stdin.write(b'more stuff\n')
print(p.stdout.readline().decode())
p.stdin.write(b'q\n')
print(p.stdout.readline().decode())
print("python finished")
p.kill()
当我运行 python 程序时,我得到了这个,然后程序永远等待下一个 readline 返回
~ $ ./test.py
Popen,pid: 27283
Hello there
我必须按 ctrl/c 才能控制回键盘。 当程序似乎挂起时,我检查了子进程是否正在运行(从另一个终端窗口)。
ps -aux | grep 27283
pi 27283 0.0 0.0 4608 596 pts/0 S+ 10:15 0:00 /bin/bash ./tst_read.sh
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。