When you run a new terminal emulator, that creates a new terminal (/dev/pts/NUMBER
on Linux). A program doesn't have to be started by that terminal to output there (try running tty
in a terminal, then in another terminal run echo hello >/dev/pts/NUMBER
). So you can tell your Python script to read and write from the terminal; all you need is to find out the path to the device file.
With xterm, it's pretty easy: run xterm -e 'tty >&3; myCommand'
with file descriptor 3 connected to a pipe from which your program reads the path to the terminal device.
p = subprocess.Popen("xterm -e 'tty >&3; exec sleep 99999999' 3>&1",
shell=True, stdout=subprocess.PIPE)
tty_path = readline(p.stdout)
tty = open(tty_path, 'r+')
Your Python program can now read and write to tty
. When you've finished, kill the terminal emulator (os.kill(p.pid, signal.SIGTERM)
).
With a terminal emulator that's based on a single process for multiple windows such as xfce4-terminal, what you want to do is considerably harder. Running xfce4-terminal
breaks links between the parent process and the child of the terminal emulator, and doesn't give you a nice PID that you can kill. You could use a named pipe to communicate but it's a bot harder to set up.
Best Answer
POSIXly: