Search code examples
pythonlinuxterminalsubprocessxterm

Sending commands to terminal


I want to pipe some commands into a Xterm window which is opened by my python program. I am on Linux and am using subprocess to comunicate with the terminal

import subprocess

subprocess.run("xterm -e python3 main.py",shell=True)

This opens a xterm window and runs the script , in the main.py file which i have called using the subprocess module contains this code :

import time

while True:
    try:
        print("Me is running")
        time.sleep(5)
    except KeyboardInterrupt:
        print("Stoped:(")
        break

I want to give commands to the linux terminal.

So if I press Ctrl+c on the terminal , it should print Stopped:( on xterm.


Solution

  • Running the subprocess in an xterm detaches you from its input and output file descriptors. The run call will block until the subprocess terminates, anyway.

    A much better solution would be to run the subprocess as a direct child with subprocess.Popen or perhaps pexpect. Run the parent in a new xterm if you like; if it doesn't perform any I/O of its own, it will seem like the subprocess is solely in control.

    The Stack Overflow subprocess tag info page has several links to questions about how interact with a running subprocess.