0

I need to achieve this:

def x():
 subprocess.Popen(...)

I cannot modify x() however I need to reach (suppress) stderr / stdout of the Popen call inside.

I need something like:

with suppress_subprocess:
 x()

...or something like that.

vpas
  • 513
  • 1
  • 5
  • 18

3 Answers3

0

return from your x function the popen object and then just access him from your caller file like so:

def x():
     return subprocess.Popen(...)


p= x()

print p.stdout
print p.stderr
print p.returncode

etc ....

ddor254
  • 1,570
  • 1
  • 12
  • 28
0

There is no direct and easy way. You would have to determine the PID of the subprocess and mess with its UNIX file descriptors, from another thread. Messy.

Chris Johnson
  • 20,650
  • 6
  • 81
  • 80
0

Sine

... I need to reach (suppress) stderr / stdout ...

have you tried the approach described here Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call?

In your case it can be something like

import io
import sys

save_stdout = sys.stdout


suppress_stdout():
    try:
        sys.stdout = io.BytesIO()
        x()
    finally:
        sys.stdout = save_stdout
Dušan Maďar
  • 9,269
  • 5
  • 49
  • 64