27_第五章-Popen调用系统命令
一、知识点
二、案例示范
1、实操截图
2、运行结果
3、源代码
# -*- coding:utf-8 -*-
#27_Popen调用系统命令
import subprocess
# popen = subprocess.Popen('dir D://',encoding='utf-8',shell=True)
#
# print(popen)
# print(popen.stdout)
#创建一个子进程执行python命令
popen = subprocess.Popen('python',stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE,shell=True)
#往python命令中传入三条参数
popen.stdin.write('print("Hello")\n'.encode('utf-8')) #encode将文本转为字节
popen.stdin.write('import os\n'.encode('utf-8')) #引入os模块
popen.stdin.write('print(os.environ)'.encode('utf-8')) #打印出python的环境变量
popen.stdin.close()
#返回过来的代码是shell(shell中默认GBK编码)运行得到的字节数据,由decode()返回GBK编码解码后的内容
# out = popen.stdout.read().decode("GBK")
# popen.stdout.close()
#
# print(out)
#第二种输出方法
out,err = popen.communicate()
print(out.decode('utf-8'))