用這個例子我在其他答案: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