subprocess模块

# coding:utf-8

import subprocess


def listdir():
	lst = subprocess.Popen("dir", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	print "strout: %s" % lst.stdout.read().decode("gbk")
	print "strerr: %s" % lst.stderr.read().decode("gbk")


if __name__ == "__main__":
	listdir()


>>>C:Python27python.exe H:/Adong_Chen_GitProject/Adong_Chen_GitProject/test/subprocessDemo.py
>>>strout: 驱动器 H 中的卷是 software
>>>卷的序列号是 0FBB-F9B2

>>>H:demo 的目录

>>>2018/09/17 23:21 <DIR> .
>>>2018/09/17 23:21 <DIR> ..
>>>2018/09/17 23:21 303 subprocessDemo.py

>>>strerr:

>>>Process finished with exit code 0

  

  提示:lst.stdout是一个文件对象,可以使用文件对象的read()方法读取

     由于Windows的cmd使用的是gbk编码,所以解码也用gbk;

原文地址:https://www.cnblogs.com/chenadong/p/9665704.html