0

I'm writing a script in which I want to be able to run a command line command, probably with os.system("stuff"). But what if my command doesn't end on its own? Like, normally in my terminal I have to ctl+C to end it. Is there a way that I can run it, stop it, and grab the output?

I'm sure there has to be but I don't know it, and I'm not sure if I know the correct terminology to find it (all my Python is self-taught from experimenting)

Thanks!

Kmanc
  • 349
  • 1
  • 5
  • 20
  • 2
    You want [the subprocess module](https://docs.python.org/3.4/library/subprocess.html), probably in combination with [a StringIO buffer](https://docs.python.org/2/library/stringio.html) to use as an in-memory output pipe. *Possibly* threads, but hopefully you can avoid them. This is a bit tricky, but hope this gives you an idea of what to look for. – Jeremy Jun 10 '16 at 23:03

2 Answers2

4

os.system() does not return the control of the subshell spawned by it, instead it returns only the exit code when the subshell is done executing the command. This can be verified by:

x = os.system("echo 'shankar'")
print(x)

What you need is the subprocess library. You can use the subprocess.Popen() function to start a subprocess. This function returns the control of the subprocess as an object which can be manipulated to control the subprocess.

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results.

Run it:

import subprocess 
proc = subprocess.Popen(['foo', 'bar', 'bar'], stdout=subprocess.PIPE, shell=True)

Hereproc is the returned object which provides control over the spawned subprocess. You can retrieve information about the process or manipulate it with this object.

proc.pid # returns the id of process

Stop it:

proc.terminate() # terminate the process.

Popen.terminate() is the equivalent of sending ctrl+c (SIGTERM) to the subprocess.

You can get the output using Popen.communicate() function.

Get output:

out, err = proc.communicate()

Note: Popen.communicate() returns output only when the subprocess has exited successfully or has been terminated or killed.

0

You can set a period of time or a loop and if condition, to kill the process with: os.kill(), to get process pid use os.getpid()

here's a reference for more info

MohammadL
  • 2,398
  • 1
  • 19
  • 36