3

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?

Aacini
  • 65,180
  • 12
  • 72
  • 108
mtmurdock
  • 12,756
  • 21
  • 65
  • 108
  • 1
    Could you show some code? It's hard to tell what you're trying to do. – Fred Foo Nov 15 '11 at 17:48
  • 3
    You could try using the [`subprocess`](http://docs.python.org/library/subprocess.html#module-subprocess) module instead of `os.system`, it has better functionality (like redirecting output) – NullUserException Nov 15 '11 at 17:52
  • Yea, lots of people have suggested this, but I cant seem to get it to work. Do you know of a good step by step example of this? I am very new to Python and most of the examples I have found assume that you know what you're doing. – mtmurdock Nov 15 '11 at 17:59
  • 1
    By 'the Python shell', do you mean IDLE? If you run it in a terminal, I think it should work. – Thomas K Nov 15 '11 at 18:18
  • @ThomasK You are totally right. Even using os.system(), if I run python from the terminal it prints properly. Put that into an answer and i'll accept it. – mtmurdock Nov 15 '11 at 18:33

2 Answers2

7

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.

Kris Harper
  • 5,672
  • 8
  • 51
  • 96
2

(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.

Thomas K
  • 39,200
  • 7
  • 84
  • 86
  • Thanks. I was testing my program in IDLE which is why I was having trouble, but the program was meant to run in the unix shell anyways. As soon as I ran it in the shell I saw the output just fine. – mtmurdock Nov 18 '11 at 05:26