Python —— 模块补充

#subprocess

stdout: 标准输出

stdin: 标准输入

stderr: 标准错误输出

subprocess是os.system的升级版,可以在python中执行shell命令,并且可以通过管道获取stdout、stdin、stderr

 1 import subprocess
 2 #这样相当于执行了ls,执行的结果直接给了屏幕
 3 #res = subprocess.Popen('ls', shell=True)
 4 #我们可以用管道把结果给接收,这里得到的res相当于那个接受了信息的管道(是一个对象)
 5 
 6 #将这个管道里的信息取出(字节形式),但注意取过一次后就空了
 7 #stdout、stdin、stderr的信息分别存于不同的管道
 8 res = subprocess.Popen('ls', shell=True,
 9                                    stdout=subprocess.PIPE,
10                                    stdin=subprocess.PIPE,
11                                    stderr=subprocess.PIPE)
12 print(res.stdout.read().decode('utf8'))
13 
14 res = subprocess.Popen('错误命令', shell=True,
15                                    stdout=subprocess.PIPE,
16                                    stdin=subprocess.PIPE,
17                                    stderr=subprocess.PIPE)
18 print(res.stderr.read().decode('utf8'))

猜你喜欢

转载自www.cnblogs.com/Matrixssy/p/12006381.html