subprocess 創建子進程執行命令語句

import subprocess

ret = subprocess.call(['ls', '-l'])
print(ret) #執行成功返回0

try:
ret = subprocess.check_call(['mv', './ab ./cd'])
print(ret)
except subprocess.CalledProcessError as e:
print(e)
執行不成功報CalledProcessError 錯, 可以用try except語句捕獲

ret = subprocess.check_output(['ls', '-l'], shell=True)
print(ret.decode())
執行結果保存在ret中
shell默認爲False,在Linux下,shell=False時, Popen調用os.execvp()執行args指定的程序;
shell=True時,如果args是字符串,Popen直接調用系統的Shell來執行args指定的程序,
如果args是一個序列,則args的第一項是定義程序命令字符串,其它項是調用系統Shell時的附加參數
以上三個方法都會等待主進程的完成

ret = subprocess.Popen(['ping www.baidu.com'], shell=True)
print('主進程結束了')

ret = subprocess.Popen(['ping www.jd.com'], shell=True)
ret.wait()
print('主進程結束了')
Popen方法不會等待子進程結束, 可以使用wait方法阻塞

ret = subprocess.Popen(['ping www.jd.com'], shell=True)
print(ret.pid) # 查看子進程pid
ret.kill()
ret.wait()

可以在Popen建立子進程的時候改變標準輸入,輸出,標準錯誤, 並通過subprocess.PIPE將多個子進程的輸入輸出綁在一起
ret = subprocess.Popen(['ls', '-l'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(ret.stdout.read().decode())
print(ret.stderr.read().decode())
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章