溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python怎么調(diào)用系統(tǒng)命令

發(fā)布時(shí)間:2023-05-10 14:25:05 來源:億速云 閱讀:152 作者:zzz 欄目:開發(fā)技術(shù)

這篇文章主要介紹“Python怎么調(diào)用系統(tǒng)命令”的相關(guān)知識,小編通過實(shí)際案例向大家展示操作過程,操作方法簡單快捷,實(shí)用性強(qiáng),希望這篇“Python怎么調(diào)用系統(tǒng)命令”文章能幫助大家解決問題。

一、os.system方法

這個(gè)方法是直接調(diào)用標(biāo)準(zhǔn)C的system() 函數(shù),僅僅在一個(gè)子終端運(yùn)行系統(tǒng)命令,而不能獲取命令執(zhí)行后的返回信息。

os.system(cmd)的返回值。如果執(zhí)行成功,那么會返回0,表示命令執(zhí)行成功。否則,則是執(zhí)行錯(cuò)誤。

使用os.system返回值是腳本的退出狀態(tài)碼,該方法在調(diào)用完shell腳本后,返回一個(gè)16位的二進(jìn)制數(shù),低位為殺死所調(diào)用腳本的信號號碼,高位為腳本的退出狀態(tài)碼。

os.system()返回值為0 linux命令返回值也為0。

os.system()返回值為256,十六位二進(jìn)制數(shù)示為:00000001,00000000,高八位轉(zhuǎn)成十進(jìn)制為 1 對應(yīng) linux命令返回值 1。

os.system()返回值為512,十六位二進(jìn)制數(shù)示為:00000010,00000000,高八位轉(zhuǎn)成十進(jìn)制為 2 對應(yīng) linux命令返回值 2。

import os
result = os.system('cat /etc/passwd')
print(result)      # 0

二、os.popen方法

os.popen()方法不僅執(zhí)行命令而且返回執(zhí)行后的信息對象(常用于需要獲取執(zhí)行命令后的返回信息),是通過一個(gè)管道文件將結(jié)果返回。通過 os.popen() 返回的是 file read 的對象,對其進(jìn)行讀取 read() 的操作可以看到執(zhí)行的輸出。

import os
result = os.popen('cat /etc/passwd')
print(result.read())

三、commands模塊

import commands
status = commands.getstatus('cat /etc/passwd')
print(status)
output = commands.getoutput('cat /etc/passwd')
print(output)
(status, output) = commands.getstatusoutput('cat /etc/passwd')
print(status, output)

四、subprocess模塊

Subprocess是一個(gè)功能強(qiáng)大的子進(jìn)程管理模塊,是替換os.system,os.spawn* 等方法的一個(gè)模塊。
當(dāng)執(zhí)行命令的參數(shù)或者返回中包含了中文文字,那么建議使用subprocess。

import subprocess
res = subprocess.Popen('cat /etc/passwd', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # 使用管道
print res.stdout.read()  # 標(biāo)準(zhǔn)輸出
for line in res.stdout.readlines():
    print line
res.stdout.close()         # 關(guān)閉

關(guān)于“Python怎么調(diào)用系統(tǒng)命令”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點(diǎn)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI