【问题标题】:How to send a new command to a subprocess如何向子进程发送新命令
【发布时间】:2023-07-06 19:35:01
【问题描述】:

我之前向question 询问过如何设置一个 tkinter gui 来接收来自子进程的行而不会使整个程序挂起。现在可以使用了。

现在,我不知道如何将新行发送到子进程。我试过使用 process.communicate,但我可能用错了。我也试过this question's solution,但self.process.stdin.write('stop\n'.encode()) 似乎不起作用。如何向子 python 子进程发送新命令?

相关代码:

self.process = subprocess.Popen([ "python", "-u", dir + "start.py" ], 
    stdout=subprocess.PIPE, 
    stdin=subprocess.PIPE, 
    stderr=subprocess.PIPE, 
    cwd=dir)

【问题讨论】:

  • 这应该可行....假设start.py 正在读取标准输入。 start.py 是否会产生大量输出(它可能挂在其输出管道上),或者它是否正在为控制终端执行“到达”标准输入的操作(例如,提示输入密码)。这是linux还是windows?
  • 您可以添加self.process.stdin.flush(),但我认为它的行缓冲了。不过值得一试。
  • 行得通!太感谢了!你想把它写成这个问题的答案,还是我应该写?
  • 我喜欢通过猜错得到正确答案的事实。我会写出来的。

标签: python python-3.x subprocess


【解决方案1】:

数据可能卡在管道中。写完后加self.process.stdin.flush()

【讨论】: