当使用pty.fork()
子进程时,它被告知它正在写入一个实际的终端,一个 tty,就像你通常使用的一样。然而,它正在写入一个 pty,一个伪终端,它是一个由另一个程序控制的 tty。
只有一个 fd,因为子程序正在将它写入终端的内容。这是标准输出、标准错误和任何终端转义码的组合。stdout/stderr 在此上下文中没有任何意义,因为它们被打印到终端,并且当程序连接到 pty 时它们不能单独访问(就像当您读取程序的输出时,您无法分辨哪个流是哪个)。
如果需要,您仍然可以将 stdout 或 stderr 重定向到文件。这将在孩子运行的代码的分叉部分中完成。您可以重定向其标准流或重定向子流程的流。
这是一个基于 sdaau 答案的示例程序(他们的答案在 Python3 中不起作用)。
#!/usr/bin/env python3
import sys
import os
import time
import pty
import subprocess
def log(chars):
sys.stdout.write(" > " + chars + "\n")
def main():
# fork this script such that a child process writes to a pty that is
# controlled or "spied on" by the parent process
(child_pid, fd) = pty.fork()
# A new child process has been spawned and is continuing from here.
# The original parent process is also continuing from here.
# They have "forked".
if child_pid == 0:
log("This is the child process fork, pid %s" % os.getpid())
log("Child process will run a subprocess controlled by the parent process")
log("All output, including this text, will be written to a pty and handled ")
log("by the parent process.")
# redirect stdout/stderr if you want to here
subprocess.run(["bash"])
else:
log("This is the parent process fork, pid %s" % os.getpid())
log("the fd being read from, %s, is not stdout nor stderr; it is " % fd)
log("simply what the child is trying to write to its tty. ")
log("stdout/stderr are combined along with terminal escape codes.")
print()
# Read initial output of child process before "typing" anything in its pty
sys.stdout.write(os.read(fd, 1024).decode())
print()
# Run any bash commands you want. I/O to the fd is handled as if you are typing
# at a terminal.
os.write(fd, "ls\n".encode())
os.write(fd, "which git\n".encode())
# you can even test tab completions
os.write(fd, "git sta\t\t".encode())
while True:
log("parent will read 1024 bytes that the child wrote to its pty")
log("if no new output is available, parent will wait. Exit with ctrl+c.\n")
# take out decode() to see raw bytes the child wrote to its pty
sys.stdout.write(os.read(fd, 1024).decode())
time.sleep(1)
if __name__ == "__main__":
main()