Find an xterm window by title, enter one command and press return using python/bash

1.6k Views Asked by At

I have an xterm window with a custom title. The xterm was fired up the following way: xterm -T customTitle.

I would like to enter a command (for example ls -l) into this xterm window from a python/bash script running on another xterm or gnome terminal, and press Return (Enter) so the command executes.

Is this possible? Is there a way of finding an active xterm by window title or pid and executing a command from another terminal?

If this cant be done programmatically, is there some python libraries out there that would let me find my window by the given title, and simulate my keyboard as if someone was entering the text?

Thanks!

2

There are 2 best solutions below

1
On

You can try this , run a command and redirect output to the xterm terminal-

>>> fp = open('/dev/pts/5','w')
>>> subprocess.Popen('ls -l',shell=True,stdout=fp, stderr=fp)

/dep/pts/5 is the file descriptor obtained from 'tty' command on your xterm !

Hope this helps !

0
On

Expanding slightly on Aro's answer, if you have a PID and want to find out the tty that process is using, a ps command like ps o tty= «PID» will serve. Substitute the actual PID number in place of «PID».

The o option to ps tells it that an output format list follows. The list in this case is tty=, which selects the controlling tty (terminal) for output and specifies a blank label for the column, which suppresses the title line. Here's an example transcript (with > prompt) from my system:

> ps o tty= 8797
pts/8
> T=$(ps o tty= 8797); echo $T
pts/8

Regarding the question of responding to a prompt, the expect command may be relevant. However, I believe you would need to write an expect script that runs on the target terminal rather than on some other controlling terminal. To do so, you might include your xterm -T customTitle command in the expect script, but it probably would be easier to say xterm -T customTitle -e somescript where somescript is an expect script or a shell script that sets stuff up and then runs expect. If the command that you are trying to automate is intended to run without any user interaction, then leave out the xterm command and just run it in a background process.