Since ECHO
is built into the Windows cmd
shell, you can't call it from Python as directly as you would call an executable (or as directly as you would call it on Linux).
i.e. this should work in your system:
import subprocess
subprocess.check_output(['notepad'])
because notepad.exe is an executable. But in Windows, echo
can only be called from inside a shell prompt, so the short way to make it work is to use shell=True
. To keep faith to your code, I would have to write
subprocess.check_output(['echo', 'hello world'], shell=True) # Still not perfect
(this, following the conditional on line 924 of subprocess.py
will expand args
into the full line 'C:\\Windows\\system32\\cmd.exe /c "echo "hello world""'
, thus calling the cmd
shell and using the shell's echo
command)
But, as @J.F.Sebastian kindly pointed out, for portability a string, and not a list, should be used to pass arguments when using shell=True
(check the links to questions on SO there). So the best way to call subprocess.check_output in your case is:
subprocess.check_output('echo "hello world"', shell=True)
The args
string is again the correct one, 'C:\\Windows\\system32\\cmd.exe /c "echo "hello world""'
and your code is more portable.
The docs say:
"On Windows with shell=True
, the COMSPEC environment variable
specifies the default shell. The only time you need to specify
shell=True
on Windows is when the command you wish to execute is built
into the shell (e.g. dir or copy). You do not need shell=True
to run a
batch file or console-based executable.
Warning: Passing shell=True
can be a security hazard if combined with untrusted
input. See the warning under Frequently Used Arguments for details. "