用这个例子我在其他答案:https://stackoverflow.com/a/43012138/3555925
你可以在这个问题的答案更多的细节。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import select
import termios
import tty
import pty
from subprocess import Popen
command = 'bash'
# command = 'docker run -it --rm centos /bin/bash'.split()
# save original tty setting then set it to raw mode
old_tty = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin.fileno())
# open pseudo-terminal to interact with subprocess
master_fd, slave_fd = pty.openpty()
# use os.setsid() make it run in a new process group, or bash job control will not be enabled
p = Popen(command,
preexec_fn=os.setsid,
stdin=slave_fd,
stdout=slave_fd,
stderr=slave_fd,
universal_newlines=True)
while p.poll() is None:
r, w, e = select.select([sys.stdin, master_fd], [], [])
if sys.stdin in r:
d = os.read(sys.stdin.fileno(), 10240)
os.write(master_fd, d)
elif master_fd in r:
o = os.read(master_fd, 10240)
if o:
os.write(sys.stdout.fileno(), o)
# restore tty settings back
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
第一个.communicate()调用很好,但是如果我尝试再次通信,会发生这种情况:'ValueError:关闭文件上的I/O操作。有没有办法让它继续运行? – justinas 2012-03-13 14:07:35
看第二个例子。 – Adam 2012-03-13 16:28:51
1-第一个代码示例可写为'stdout = subprocess.check_output(['ls','-lash'])''。要运行'bash'命令,你可以'check_output(“some && command $(
jfs
2016-02-04 14:27:35