Python 執行終端命令的方法

import os
import subprocess
'''
os.system模塊
os.system("ls -hl") 執行命令並返回狀態碼,當返回0表示成功;返回256表示失敗,痛點是無法返回output

os.popen模塊
os.popen("ls -hl") 執行命令,之後通過.read()方法獲取output返回值

subprocess模塊
subprocess.getstatusoutput("ls -hl") 執行命令,並返回狀態status、輸出output
subprocess.getoutput("ls -hl")       執行命令,只返回輸出結果output
subprocess.call("ls -hl")            執行命令並返回狀態碼 和os.system("ls -hl")類似
'''


def test_system(cmd):
    status = os.system(cmd) # 會自動輸出output到控制檯 但是無法接收,status爲0表示成功、status爲256表示失敗
    print(status)


def test_popen(cmd):
    output = os.popen(cmd).read() # 只會獲取到命令的output,如果是有output的錯誤命令 會輸出output,否則輸出空白
    print(output)


def test_getoutput(cmd):
    output = subprocess.getoutput(cmd) # 和os.popen(cmd)類似
    print(output)


def test_getstatusoutput(cmd):
    status, output = subprocess.getstatusoutput(cmd) # 執行命令,並返回狀態status、輸出output
    print(status)
    print(output)


def test_call(cmd):
    status = subprocess.call(cmd) # 和os.system(cmd)類似
    print(status)


if __name__ == '__main__':
    # test_system('ls -lh')  # test_system('test')
    # test_popen('pwd') # test_popen('test')
    # test_getoutput('pwd')
    # test_getstatusoutput('pwd')
    test_call('pwd')
發佈了264 篇原創文章 · 獲贊 202 · 訪問量 110萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章