0

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.

MrHola21
  • 301
  • 2
  • 8

2 Answers2

1

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • What does I/O of its own mean , If I add an argument that if ctrl+c is pressed on the parent terminal all the text in the x-term has to written to file. would that be an I/O ?? – MrHola21 Jul 15 '21 at 14:10
  • If the parent script prints something to the terminal, you can't tell if it was printed by the parent or the child. Similarly, if the parent needs to read keyboard input, it can't (without cooperation from the child process). – tripleee Jul 15 '21 at 15:21
  • So how do i actually do it ? I have been strugging for many hours with this. I saw the questions with tags of subprocess – MrHola21 Jul 17 '21 at 08:31
  • 1
    https://stackoverflow.com/questions/7897202/subprocess-readline-hangs-waiting-for-eof seems to have several viable solutions. `pexpect` is probably overkill here, but could still be the simplest solution. If you insist on using `subprocess`, closing the parent process file descriptor to `stdin` might be necessary in order to let the child take over. – tripleee Jul 17 '21 at 09:57
-2

i think its not possible to run commands on xterm or cmd using subprocess. subprocess is used to execute the program directly. Not from a cmd or xterm. And also cmd or xterm doesn't takes any arguments

Mrinmoy Haloi
  • 143
  • 1
  • 7
  • This is confused on several points. `xterm` does allow you to specify a command to run, and running `xterm` in a subprocess is perfectly fine (though I would generally recommend against it; many times, a better solution is to not have Python meddle with the user's GUI directly). – tripleee Jul 14 '21 at 09:20