我正在尝试创建一个与/ bin / bash shell交互并获取信息或执行命令的进程。我不想关闭该过程,因为我想保留状态以供将来进行交互。
我尝试了在SO answer上的解决方案,但是该过程在一次通信后终止。
通过pythonsubprocess
API,我发现subprocess.check_output()
非常适合。但是,类似于Popen.communicate()
,这会在执行一次后杀死进程。
最后一种似乎可行但不安全并导致死锁的方法是使用Popen.stdin.write
和Popen.stdout.read
。如果找不到EOF,则读取操作将无限期等待。
是否有更安全,更简单的方法来实现这一目标?
编辑:我尝试过的更多内容:
import subprocess
import select
import os
process = subprocess.Popen(['/bin/bash'], shell=True, text=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.stdin.write('export SOMETHING=10000abc\n')
process.stdin.flush()
process.stdin.write('echo $SOMETHING\n')
process.stdin.flush()
r, w, e = select.select([process.stdout], [process.stdin], [], 0)
if process.stdout in r:
print (os.read(process.stdout.fileno(), 50))
else:
print ("Nothing to read")
此输出始终为Nothing to read
我最终做了以下事情:
import subprocess
import select
import os
process = subprocess.Popen(['/bin/bash'], shell=True, text=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.stdin.write('export SOMETHING=10000abc\n')
process.stdin.flush()
process.stdin.write('echo $SOMETHING\n')
process.stdin.flush()
r, w, e = select.select([process.stdout], [process.stdin], [], 0.1)
result = ""
while process.stdout in r:
result += os.read(process.stdout.fileno(), 100).decode("utf-8")
r, w, e = select.select([process.stdout], [], [], 0.1)
process.kill()
print (result)