日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python运行命令_Python中执行外部命令

發布時間:2025/3/15 python 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python运行命令_Python中执行外部命令 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

有很多需求需要在Python中執行shell命令、啟動子進程,并捕獲命令的輸出和退出狀態碼,類似于Java中的Runtime類庫。

subprocess模塊的使用:

Python使用最廣泛的是標準庫的subprocess模塊,用來替換os.system(),os.spawn*(),os.popen*()和commands.*等模塊與函數。

使用subprocess最簡單的方式就是用它提供的便利函數,call,check_all與check_output,當便利函數滿足不了要求再使用Popen類。

1. call

subprocess(args,*,stdin=None,stout=None,stderr=None,shell=False)

shell=True,Python會先運行一個shell,再用shell解釋字符串,而不是傳遞一個列表。

2. check_call

check_all與call類似,只是遇到異常情況返回的形式不同,它會拋出subprocess.CalledProcessError異常

3. check_output

這個便利函數是使用最多了,它可以獲取命令的結果,而不是退出狀態碼

如果想要捕捉退出狀態碼,可以通過拋出的subprocess.CalledProcessError異常

import subprocess

try:

output = subprocess.check_output('ls /zz',shell=True)

except subprocess.CalledProcessError as e:

output = e.output

code = e.returncode

print (code,output)

執行結果:

如果想捕獲命令的錯誤輸出,需將錯誤輸出重定向到標準輸出

subprocess.check_output(['cmd','arg1','arg2'],stderr=subprocess.STDOUT)

4. 使用Popen

下面的exexute_cmd函數對Popen,進行了封裝,執行成功,返回標準輸出和狀態碼,失敗是返回狀態碼和錯誤輸出。

#!/usr/bin/python

#coding=utf8

import subprocess

def execute_cmd(cmd):

p = subprocess.Popen(cmd,

shell=True,

stdin=subprocess.PIPE,

stdout=subprocess.PIPE,

stderr=subprocess.PIPE)

stdout, stderr = p.communicate()

if p.returncode != 0:

return p.returncode, stderr

return p.returncode, stdout

if __name__=='__main__':

cmd='ls /u01'

returncode,out=execute_cmd(cmd)

if returncode != 0:

raise SystemExit('execute {0} err :{1}'.format(cmd,out))

else:

print("execute command ({0} sucessful)".format(cmd))

目錄不存時:

總結

以上是生活随笔為你收集整理的python运行命令_Python中执行外部命令的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。