subprocess的常用用法
"""
Description:
Author:Nod
Date:
Record:
#---------------------------------v1-----------------------------------#
""" import subprocess
import time # 正确的命令通过管道输出
obj = subprocess.Popen('ping 127.0.0.1', shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
print('\033[31;1m执行结果1\033[0m')
print(obj.stdout.read().decode('gbk')) # 不正确的命令通过管道输出
obj = subprocess.Popen('12ping 127.0.0.1', shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE, )
print('\033[31;1m执行结果2\033[0m')
print(obj.stderr.read().decode('gbk')) # 执行一串命令的方式1 tasklist | findstr python
obj = subprocess.Popen(
'tasklist | findstr python', shell=True,
stdout=subprocess.PIPE, # 命令的正确结果进入管道
stderr=subprocess.PIPE, # 命令的错误结果进入另外1个管道 )
print('\033[31;1m执行结果3\033[0m')
print(obj.stdout.read().decode('gbk')) # 执行一串命令的方式2
obj2 = subprocess.Popen(
'tasklist', shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
# 此处会将obj2的执行结果输入给obj2 stdin=obj2.stdout,
obj3 = subprocess.Popen(
'findstr python',
shell=True,
stdin=obj2.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
print('\033[31;1m执行结果4\033[0m')
print(obj3.stdout.read().decode('utf-8'))