python_day6 subprocess模块,

os.system功能,不直接打印到屏幕,而是传递参数

如果想将结果放入变量再随意打印 就需要 subprocess 模块了

将执行结果丢入管道(正确的进stdout,错误的进stderr, 执行双命令,第二个命令  用stdin);管道的值只能取一次

import subprocess
subprocess.Popen('dir',shell=True) -->直接打印

res=subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE)
-->结果扔进管道 stdout->subprocess.PIPE
JG=res.stdout.read().decode('gbk')-->字符编码参考当前软件
print(JG)


res=subprocess.Popen('abcddir',shell=True,stdout=process.PIPE,
stderr=subprocess.PIPE)

JG=res.stdout.read().decode('gbk')-->没结果
print(JG)

ERR=res.stderr.read().decode('gbk')
print(ERR) -->打印错误信息


##stdin-->管道功能,(爬虫可以使用,爬下来之后传递给下面截取)

res=subprocess.Popen('ls /|grep bin',shell=True,stdout=process.PIPE)
print(res)

等于这种:
res=subprocess.Popen('ls /',shell=True,
stdout=process.PIPE)


res1=subprocess.Popen('grep bin',shell=True,
stdin=res.stdout, -->res的结果作为这里的输出
stdout=process.PIPE)

原文地址:https://www.cnblogs.com/onda/p/6955062.html