调用外部程序

'''
1. os.system() 阻塞式调用

import os
os.system("mspaint")
print("after call")

ret=os.system("dir sdfdsf") 返回的是退出码
print(ret)
'''
'''
2. subprocess 阻塞式调用
目的:
1. 获取应用程序的输出
通常使用check_output,
from subprocess import check_output
ret = check_output("dir",shell=True,encoding="gbk") 获取了应用程序的输出值,也是阻塞式的,需要等待程序完成才能退吹
shell 使用shell打开
encoding: 确定编码方案和解码方案
'''
'''
3. subprocess中的Popen. 非阻塞式调用
from subprocess import Popen,PIPE
ret= Popen(args=,stdin=,stdout=,stderr=,shell=True,encoding="gbk")
运行时的时候也可以进行输出
shell=True 的时候,用shell去运行,args是一个字符串的传参,比较常用.
shell=False 的时候,用shell去运行,args是一个列表的传参

popen获取外部程序的输出
from subprocess import Popen,PIPE
res= Popen(args="dir",stdout=PIPE,stderr=PIPE,shell=True,encoding="gbk") PIPE是获取输出的内容,不让其输出在屏幕上,而是转到管道中.
output,error = res.communicate() 返回程序输出的内容.(output:标准输出,error: 标准错误,默认标准输出/错误是打印在屏幕上,通过PIPE现在是可以定向到变量中去)

'''
from subprocess import Popen,PIPE
rt= Popen(args="dir sadas",stdout=PIPE,stderr=PIPE,shell=True,encoding="gbk")
output,error = rt.communicate()

print("output:",output)
print("----------------------")
print("error:",error)

原文地址:https://www.cnblogs.com/wenshu/p/12267075.html