0

I want to block the output that becomes visible when I run subprocess.call().
That's the only output I want to stop, because I need the commands that run after to display.

The call is showing my password which I have set as a system variable hidden as %%mypassword%% in the file getting executed (however, it shows up in the command line interface).

from subprocess import call
with open('//path/pwhold.txt','w') as pwhold:
        call(r"\\filetorun\%s.bat" % DB,stdout=pwhold)
os.unlink('//path/pwhold.txt')

This sort of works, but the file isn't deleted until after execution of the file is complete.

Are there any other ways to do this?

Josh Correia
  • 2,133
  • 1
  • 17
  • 29
Chet Meinzer
  • 1,475
  • 2
  • 17
  • 31
  • just use `os.devnull` instead of `'//path/pwhold.txt'` as said in [the page I've linked above](http://stackoverflow.com/a/11269627/4279). – jfs Mar 07 '14 at 01:30

1 Answers1

1

Per Sebastion's comments. The interface used by subprocess.call() requires an actual file handle in order to capture the output at the OS level. Attempting to use a string or string buffer fails when executing the command.

IGNORE: This does not work: Redirect STDOUT to a string instead of a file. That way your information only appears in memory. See this question.

TLDR use:

from cStringIO import StringIO
import sys

old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()

OR

from io import TextIOWrapper, BytesIO

# setup the environment
old_stdout = sys.stdout
sys.stdout = TextIOWrapper(BytesIO(), sys.stdout.encoding)
Josh Correia
  • 2,133
  • 1
  • 17
  • 29
WombatPM
  • 2,293
  • 2
  • 18
  • 20
  • Replacing `sys.stdout` won't affect a child process. OP can [use `os.devnull` file instead](http://stackoverflow.com/questions/11269575/how-to-hide-output-of-subprocess-in-python-2-7). In general, if you want to [redirect at C level, you need something like `os.dup()` on Unix](http://stackoverflow.com/a/17954769/4279) (it might work on Windows, I haven't tried) – jfs Mar 06 '14 at 23:36
  • You are right. but if you say mystdout = StringIO() and then modify the call to be call(r"\\filetorun\%s.bat" % DB,stdout=mystdout) this approach would work right? – WombatPM Mar 06 '14 at 23:40
  • after doing this: mystdout = StringIO() this did not work: call(r"\\filepathxxx\temp\%s.bat" % DB,stdout=mystdout) is that what you were talking about? can you show me how this is implemented. – Chet Meinzer Mar 07 '14 at 01:09
  • -1: it seems I wasn't clear enough. Your solution does not work. To see it, you could try to run any subprocess that prints something. – jfs Mar 07 '14 at 01:20
  • Thanks, the FNULL solution from other post "How to hide output of subprocess in Python 2.7" works.:FNULL=open(os.devnull,'w'); subprocess.call(r"file.bat",stdout=FNULL,stderr=subprocess.STDOUT); FNULL.close() – Chet Meinzer Mar 07 '14 at 01:30