day5_python之subprocess模块

subprocess作用:用来执行系统命令
它会开启一个子进程,通过子进程去执行一些命令

读取正确的命令执行结果,如果没有指定把结果输出到哪里,默认打印到屏幕上
#subprocess.Popen(r'dir D:python-笔记day5', shell=True)  #shell等于True ,代表执行的是shell命令

###把命令执行的结果先扔到管道里边去,等需要的时候再取
res = subprocess.Popen(r'dir D:python-笔记day5',shell=True,
                 stdout=subprocess.PIPE,
                 stderr=subprocess.PIPE)

print(res.stdout.read().decode('gbk'))    #从管道里读取正确的标准输出,#结果只有一次,读走就没了,第二次再读没有内容

 

错误的命令执行结果,如果没有指定把结果输出到哪里,默认打印到屏幕上

 

import subprocess
res = subprocess.Popen(r'hah D:python-笔记day5',shell=True,
                 stdout=subprocess.PIPE,
                 stderr=subprocess.PIPE)    #hah不是正确的命令,命令执行结果会保存到stderr

print(res.stdout.read().decode('gbk'))    #从stdout里读取不到内容,错误的结果保存到stderr

print(res.stderr.read().decode('gbk'))  #结果只有一次,读走就没了,第二次再读没有内容

#'hah' 不是内部或外部命令,也不是可运行的程序或批处理文件。

  


原文地址:https://www.cnblogs.com/xiechao621/p/7887673.html