1

I usually write bash scripts, but I am writing one now in python. So I have the problem that I want to run an interactive command which asks for some user data, so ideally I would like to pass control of stdin, stdout to bash, and then go back to my python script when the command has been executed correctly.

Problem is: I haven't been able to do it with os.system. And I would also like to capture the exit status of the command that I run.

RedX
  • 14,749
  • 1
  • 53
  • 76
fazineroso
  • 7,196
  • 7
  • 31
  • 42

1 Answers1

1
from subprocess import Popen, STDOUT, PIPE
from time import sleep

x = Popen('du -h', shell=True, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
while x.poll() == None:
    sleep(0.25)
print('Command finished successfully with the following exit status:',x.poll())
print('And this was the output given by the command:')
print(x.stdout.read())
x.stdout.close()
x.stdin.close()
Torxed
  • 22,866
  • 14
  • 82
  • 131
  • @falsetru old habbit. sorry. They do the same thing tho so won't affect the outcome very much. Since you would still have to do a loop and sleep, the only difference is you're calling `.poll()` instead of `.wait()` which to me sounds more intuative to poll for a exit code rather than waiting.. but i guess it's up to each and every one :) – Torxed Feb 04 '14 at 13:22