I want to make a simple batch script using python using os.system. I am able to run the commands just fine, but the output for those commands dont print to the python shell. Is there some way to redirect the output to the python shell?
2 Answers
You can use subprocess.
from subprocess import Popen, PIPE
p1 = Popen(['ls'], stdout=PIPE)
print p1.communicate()[0]
This will print the directory listing for the current directory. The communicate() method returns a tuple (stdoutdata, stderrdata). If you don't include stdout=PIPE or stderr=PIPE in the Popen call, you'll just get None back. (So in the above, p1.communicate[1] is None.)
In one line,
print Popen([command], stdout=PIPE).communicate()[0]
prints the output of command to the console.
You should read more here. There's lots more you can do with Popen and PIPE.
Comments
(Reposting as an answer as requested):
os.system() will work when run in a terminal - that's where stdout is going, and any processes you start will inherit that stdout unless you redirect it.
If you need to redirect into IDLE, use @root45's answer above (upvoted). That will work for most programs, but at least on Unixy systems, processes can also directly access the terminal they're run in (e.g. to request a password) - Windows may have something similar.
subprocessmodule instead ofos.system, it has better functionality (like redirecting output)