調用外部程序

'''
1. os.system() 阻塞式調用shell

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()spa

print("output:",output)
print("----------------------")
print("error:",error)字符串

相關文章
相關標籤/搜索