Yes, redirecting sys.stdout
only works for python prints. When a sub-process is invoked through subprocess
, python doesn't capture the output by default, and leaves the process execute normally. There's no way to remove the output from the process easily.
I suppose you could create a subprocess.py
file at the same level as the python code you cannot change (or before the official subprocess.py
) to change Popen
contents, but that would mean import the official module from your stub module, hardcoding python path, ... Doable, but there's a simpler approach.
Here's a quick hack for python 3 that I tested and which works:
- locate the file
subprocess.py
in the python installation and copy it aside the module that you cannot change (on my machine C:\python34\lib\subprocess.py
)
- add just one line in that file
the code (around line 750):
def __init__(self, args, bufsize=-1, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS,
shell=False, cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0,
restore_signals=True, start_new_session=False,
pass_fds=()):
"""Create new Popen instance."""
_cleanup()
now add (before _cleanup()
):
stderr = stdout = DEVNULL
that forces standard output and error to null device: no output
now the drawbacks:
- dependent of the installed python version. Could work with other versions but it's not recommended to mix packages.
- copies the whole
subprocess.py
file instead of just patching the needed calls
Apart from that it's a 5 minute job and it works. I recommend that you keep that as a temporary solution and you do something about this "code that cannot be changed" at some point.