import subprocess
# Create test file.
with open('test.cmd', 'w') as w:
w.write(
'@echo off\n'
'echo 1 stdout\n'
'>&2 echo 2 stderr\n'
'>&3 echo 3 program output\n')
output = subprocess.check_output(
'test.cmd 1>nul',
universal_newlines=True,
shell=True)
print('check_output:', repr(output))
The example will get the programs output from handle 3. The program
here is just an echo
to mimic a program though the redirection
is the goal.
CMD supports up to 9 output handles as quoted from the SS64 site:
STDIN = 0 Keyboard input
STDOUT = 1 Text output
STDERR = 2 Error text output
UNDEFINED = 3-9
You can output programs to handle 3 in the batch file.
Then you can redirect handle 1 to nul
i.e. 1>nul
or
just >nul
in the Python file.
Thus, check_output
will only output handle 3 as the stdout.
Output:
2 stderr
check_output: '3 program output\n'
- Output uses
repr()
to show output in 1 line for testing.
- No output of the line
1 stdout
as handle 1 was redirected to nul.
- Stderr will still print out to console as it is not redirected.
You can choose how to handle stderr.
If the Stanford Parser outputs the data as stderr (handle 2)
instead of stdout (handle 1), then you may use 2>&3
in the batch file command to redirect to handle 3. i.e.
2>&3 java -cp stanford-parser.jar ...
I have no experience with the Stanford Parser so the command
example is a guess from online examples from stanford.edu.
If you want all of the output instead of just program output
and the program outputs to handle 2. Then use in the
check_output
with 2>&1
or the recommended argument
stderr=subprocess.STDOUT
and omit the 1>nul
. This may
include batch file script errors which may be undesirable.
If possible, rewrite the batch file to Python as you avoid
complication and 1 script gets all the control.