Python模块subprocess

subprocess的常用用法

 1 """
 2 Description:
 3 Author:Nod
 4 Date:
 5 Record:
 6 #---------------------------------v1-----------------------------------#
 7 """
 8 
 9 import subprocess
10 import time
11 
12 # 正确的命令通过管道输出
13 obj = subprocess.Popen('ping 127.0.0.1', shell=True,
14                        stdout=subprocess.PIPE,
15                        stderr=subprocess.PIPE,
16                        )
17 print('33[31;1m执行结果133[0m')
18 print(obj.stdout.read().decode('gbk'))
19 
20 # 不正确的命令通过管道输出
21 obj = subprocess.Popen('12ping 127.0.0.1', shell=True,
22                        stdout=subprocess.PIPE,
23                        stderr=subprocess.PIPE,
24 
25                        )
26 print('33[31;1m执行结果233[0m')
27 print(obj.stderr.read().decode('gbk'))
28 
29 # 执行一串命令的方式1   tasklist | findstr python
30 obj = subprocess.Popen(
31     'tasklist | findstr python', shell=True,
32     stdout=subprocess.PIPE,  # 命令的正确结果进入管道
33     stderr=subprocess.PIPE,  # 命令的错误结果进入另外1个管道
34 
35 )
36 print('33[31;1m执行结果333[0m')
37 print(obj.stdout.read().decode('gbk'))
38 
39 # 执行一串命令的方式2
40 obj2 = subprocess.Popen(
41     'tasklist', shell=True,
42     stdout=subprocess.PIPE,
43     stderr=subprocess.PIPE,
44 )
45 # 此处会将obj2的执行结果输入给obj2   stdin=obj2.stdout,
46 obj3 = subprocess.Popen(
47     'findstr python',
48     shell=True,
49     stdin=obj2.stdout,
50     stdout=subprocess.PIPE,
51     stderr=subprocess.PIPE,
52 )
53 print('33[31;1m执行结果433[0m')
54 print(obj3.stdout.read().decode('utf-8'))
View Code
原文地址:https://www.cnblogs.com/nodchen/p/8995746.html