How to use subprocess.Popen with built-in command on Windows
17,667
You should use call subprocess.Popen
with shell=True
as below:
import subprocess
result = subprocess.Popen("dir c:", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output,error = result.communicate()
print (output)
More info on subprocess module.
Author by
Xiaojun Chen
Updated on June 04, 2022Comments
-
Xiaojun Chen almost 2 years
In my old python script, I use the following code to show the result for Windows cmd command:
print(os.popen("dir c:\\").read())
As the python 2.7 document said
os.popen
is obsolete andsubprocess
is recommended. I follow the documentation as:result = subprocess.Popen("dir c:\\").stdout
And I got error message:
WindowsError: [Error 2] The system cannot find the file specified
Can you tell me the correct way to use the
subprocess
module? -
Eryk Sun over 7 yearsUsing
shell=True
for internal shell commands such asset
anddir
is generally a bad idea. The output uses a lossy ANSI encoding. Windows environment variables and filesystem names are UTF-16, so generally internal shell commands should be run with the/u /c
option to make cmd output UTF-16. The output then has to be decoded as'utf-16le'
. It can't be done withshell=True
because/c /u
is in the wrong order.