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?

5
  • 1
    Could you show some code? It's hard to tell what you're trying to do. Commented Nov 15, 2011 at 17:48
  • 3
    You could try using the subprocess module instead of os.system, it has better functionality (like redirecting output) Commented Nov 15, 2011 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. Commented Nov 15, 2011 at 17:59
  • 1
    By 'the Python shell', do you mean IDLE? If you run it in a terminal, I think it should work. Commented Nov 15, 2011 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. Commented Nov 15, 2011 at 18:33

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.