Reputation: 1255
I have a the following python program which open a command as subprocess and displays its output. This command though waits for user input after displaying information. I on the other hand want to get that information and close this subprocess and get back to what program is doing
Program is this
#!/usr/bin/python
from commands import *
import subprocess, os, sys, time
cmd = '/usr/local/bin/astrisctl reset'
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
time.sleep( 5 )
p.kill()
out = p.stderr
if out == '' and p.poll() != None:
print "No output from the commnand"
sys.exit()
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
print "i am back"
i want something like
something something
0) xyz-0008E8
1) xyz-000AB9
2) xyz-000D18
3) xyz-000D2B
4) xyz-000E9D
pick a choice
i am back
but comes like
dta-rack-04:~ admin$ python Desktop/getBurnInLogs.py
something something
0) xyz-0008E8
1) xyz-000AB9
2) xyz-000D18
3) xyz-000D2B
4) xyz-000E9D
Choose a device: Traceback (most recent call last):
File "Desktop/getBurnInLogs.py", line 16, in <module>
sys.stdout.write(out)
but i am hoping
something something
0) xyz-0008E8
1) xyz-000AB9
2) xyz-000D18
3) xyz-000D2B
4) xyz-000E9D
pick a choice
i am back
Main purpose is to not wait for that choice.
Also if you could suggest a good way to get this options in list looking like {'xyz-000E9D', 'xyz-000E9D'..... etc etc}
Thanks a lot for your help and time
Upvotes: 0
Views: 3378
Reputation: 36782
If you want to send it SIGKILL then use
p.kill()
This should kill the process immediately
If you want to wait for it to finish (which it doesn't sound like you do), then use
p.wait()
UPDATE: in the case that the output is coming from stdout and not stderr, you'll need to capture that. Since you're doing some weird stuff, you'll want to make it unbuffered
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, bufsize=0)
and then read from p.stdout
, handle with care.
You can also get rid of shell=True
pretty easily
cmd = ['/usr/local/bin/astrisctl', 'reset']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=0)
Upvotes: 1