用Python調用Shell命令

Python常常被稱做「膠水語言」,由於它可以輕易地操做其餘程序,輕易地包裝使用其餘語言編寫的庫,也固然能夠用Python調用Shell命令。python

用Python調用Shell命令有以下幾種方式:linux

第一種:os.system

os.system("The command you want").shell

 

 

這個調用至關直接,且是同步進行的,程序須要阻塞並等待返回。返回值是依賴於系統的,直接返回系統的調用返回值,因此windows和linux是不同的。編程

 

第二種:os.popen

os.popen(command[,mode[,bufsize]])windows

先給你們看個例子api

能夠看出,popen方法經過p.read()獲取終端輸出,並且popen須要關閉close().當執行成功時,close()不返回任何值,失敗時,close()返回系統返回值. 可見它獲取返回值的方式和os.system不一樣。安全

 

 

第三種,使用commands ( python3失效)

根據你須要的不一樣,commands模塊有三個方法可供選擇。getstatusoutput, getoutput, getstatus。session

commands.getstatusoutput(cmd) 返回(status, output). commands.getoutput(cmd) 只返回輸出結果 commands.getstatus(file) 返回ls -ld file的執行結果字符串,調用了getoutput,不建議使用此方法

可是,如上三個方法都不是Python推薦的方法,並且在Python3中其中兩個已經消失。app

 

第四種,subprocess《Python文檔中目前全力推薦》

subprocess使用起來一樣簡單:spa

直接調用命令,返回值便是系統返回。shell=True表示命令最終在shell中運行。Python文檔中出於安全考慮,不建議使用shell=True。建議使用Python庫來代替shell命令,或使用pipe的一些功能作一些轉義。官方的出發點是好的,不過真心麻煩了不少, so....

 

可是,我使用subprocess失敗了

>>> import subprocess >>> subprocess.call("cat %s |grep %s > %s " % ("/home/www/running/os-app-api/nohup.out","2019-10-28","~/nohup-2019-10-28.out")) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python3.6/subprocess.py", line 287, in call with Popen(*popenargs, **kwargs) as p: File "/usr/lib64/python3.6/subprocess.py", line 729, in __init__ restore_signals, start_new_session) File "/usr/lib64/python3.6/subprocess.py", line 1364, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'cat /home/www/running/os-app-api/nohup.out |grep 2019-10-28 > ~/nohup-2019-10-28.out ': 'cat /home/www/running/os-app-api/nohup.out |grep 2019-10-28 > ~/nohup-2019-10-28.out '

可是。。我能夠直接運行在shell裏面:

一樣的 我用os.system 去運行,也確實產生了。。好奇

>>> import os >>> os.system("cat %s |grep %s > %s " % ("/home/www/running/os-app-api/nohup.out","2019-10-28","~/nohup-2019-10-28.out")) 256

 源碼研究:

這裏面最爲重要的幾個參數是:. args:要執行的shell命令,或者是命令的列表; bufsize:緩衝區大小;。 stdin、stdout、stderr:表示程序的標準輸入、標準輸出以及錯誤輸出。 shell:是否直接執行命令,若是設置爲True就表示能夠直接執行; cwd:當前的工做目錄; env:子進程環境變量;

案例:

 

 subprocess模塊裏面還有一項功能比較強大的支持在於能夠直接使用標準輸入、標準輸出和錯誤輸出進行進程的數據通信操做。

    例如,在Python安裝完成以後都會存在有交互式的編程環境,那麼本次將經過程序調用交互式編程環境。

直接操做python命令行,在python命令行中直接輸入程序。

def main(): subp_popen=subprocess.Popen("python.exe",stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) subp_popen.stdin.write("print('subp_popen.stdin.write1')\n".encode()) subp_popen.stdin.write("print('subp_popen.stdin.write2')\n".encode()) subp_popen.stdin.write(("print('subp_popen.stdin.write3'+1)").encode()) subp_popen.stdin.close() cmd_out=subp_popen.stdout.read() subp_popen.stdout.close() print(cmd_out.decode()) cmd_err=subp_popen.stderr.read() subp_popen.stderr.close() print(cmd_err) if __name__ == '__main__': main()

結果:

相關文章
相關標籤/搜索