How to use subprocess.Popen with built-in command on Windows

 ̄綄美尐妖づ 提交于 2021-02-07 10:01:07

问题


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 and subprocess 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?


回答1:


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.




回答2:


This works in Python 3.7:

from subprocess import Popen, PIPE

args = ["echo", "realtime abc"]
p = Popen(args, stdout=PIPE, stderr=PIPE, shell=True, text=True)

for line in p.stdout:
    print("O=:", line)

.

Output:

O=: "realtime abc"



来源:https://stackoverflow.com/questions/39716557/how-to-use-subprocess-popen-with-built-in-command-on-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!