3

I need to capture the stdout of a process I execute via subprocess into a string to then put it inside a TextCtrl of a wx application I'm creating. How do I do that?

EDIT: I'd also like to know how to determine when a process terminates

kettlepot
  • 10,574
  • 28
  • 71
  • 100

2 Answers2

10

From the subprocess documentation:

from subprocess import *
output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
Blair Conrad
  • 233,004
  • 25
  • 132
  • 111
  • output = subprocess.Popen("echo hello", stdout=subprocess.PIPE).communicate()[0] gives an error that says "Impossible to find the specified file"; what is the problem? – kettlepot Aug 12 '10 at 23:28
  • 1
    If you want to execute a whole command in a string, you have to pass `shell=True`. Otherwise, you need to pass the command and args as a list of strings: `subprocess.Popen(["echo", "hello"], stdout=subprocess.PIPE).communicate()[0]` – Walter Mundt Aug 12 '10 at 23:38
  • It will blocking the program. – towry Jan 18 '21 at 07:29
2

Take a look at the subprocess module.

http://docs.python.org/library/subprocess.html

It allows you to do a lot of the same input and output redirection that you can do in the shell.

If you're trying to redirect the stdout of the currently executing script, that's just a matter of getting a hold of the correct file handle. Off the top of my head, stdin is 0, stdout is 1, and stderr is 2, but double check. I could be wrong on that point.

haydenmuhl
  • 5,998
  • 7
  • 27
  • 32