日常整理python執(zhí)行系統(tǒng)命令的常見方法(全)
具體內(nèi)容如下:
1 os.system
例如 ipython中運行如下命令,返回運行狀態(tài)status
os.system('cat /etc/passwdqc.conf')
min=disabled,24,11,8,7
max=40
passphrase=3
match=4
similar=deny
random=47
enforce=everyone
retry=3
Out[6]: 0
2 os.popen()
popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.
運行返回結(jié)果
In [20]: output = os.popen('cat /proc/cpuinfo')
In [21]: lineLen = []
In [22]: for line in output.readlines():
lineLen.append(len(line))
....:
In [23]: line
line lineLen
In [23]: lineLen
Out[23]:
[14,
25,
...
3 如何同時返回結(jié)果和運行狀態(tài),commands模塊:
#String form: <module 'commands' from '/usr/lib64/python2.7/commands.pyc'> File: /usr/lib64/python2.7/commands.py Docstring: Execute shell commands via os.popen() and return status, output. Interface summary: import commands outtext = commands.getoutput(cmd) (exitstatus, outtext) = commands.getstatusoutput(cmd) outtext = commands.getstatus(file) # returns output of "ls -ld file" A trailing newline is removed from the output string. Encapsulates the basic operation: pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r') text = pipe.read() sts = pipe.close()
commands示例如下:
In [24]: (status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
In [25]: status
Out[25]: 0
In [26]: len(output)
Out[26]: 3859
4 使用模塊subprocess
ipython 中運行"?subprocess"可以發(fā)現(xiàn)subprocess是python用來替換os.popen()等管道操作命令的新模塊
A more real-world example would look like this:
try: retcode = call("mycmd" + " myarg", shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e
相對于上面幾種方式,subprocess便于控制和監(jiān)控進程運行結(jié)果,subprocess提供多種函數(shù)便于應(yīng)對父進程對子進程不同要求:
4.1.1 subprocess.call()
父進程父進程等待子進程完成,返回exit code
4.1.2 subprocess.check_call()
父進程等待子進程完成,返回0,如果returncode不為0,則舉出錯誤subprocess.CalledProcessError,該對象包含有returncode屬性,可用try...except...來檢查
4.1.3 subprocess.check_output()
父進程等待子進程完成
返回子進程向標(biāo)準(zhǔn)輸出的輸出結(jié)果
檢查退出信息,如果returncode不為0,則舉出錯誤subprocess.CalledProcessError,該對象包含有returncode屬性和output屬性,output屬性為標(biāo)準(zhǔn)輸出的輸出結(jié)果,可用try...except...來檢查
例如:
In [32]: out = subprocess.call("ls -l", shell=True)
total 42244
-rw-rw-r--. 1 *** *** 366 May 26 09:10 ChangeLog
4.2.1
上面三個函數(shù)都是源于Popen()函數(shù)的wapper(封裝),如果需要更加個性化應(yīng)用,那么就需要使用popen()函數(shù)
Popen對象創(chuàng)建后,主程序不會自動等待子進程完成。我們必須調(diào)用對象的wait()方法,父進程才會等待 (也就是阻塞block)
[wenwt@localhost syntax]$ rm subprocess.pyc [wenwt@localhost syntax]$ python process.py parent process [wenwt@localhost syntax]$ PING www.google.com (173.194.219.99) 56(84) bytes of data. ^C [wenwt@localhost syntax]$ --- www.google.com ping statistics --- 5 packets transmitted, 0 received, 100% packet loss, time 3999ms
加上wait方法:
[wenwt@localhost syntax]$ python process.py PING www.google.com (173.194.219.103) 56(84) bytes of data. --- www.google.com ping statistics --- 5 packets transmitted, 0 received, 100% packet loss, time 3999ms parent process
補充介紹:Python 執(zhí)行終端命令的方法
import os import subprocess ''' os.system模塊 os.system("ls -hl") 執(zhí)行命令并返回狀態(tài)碼,當(dāng)返回0表示成功;返回256表示失敗,痛點是無法返回output os.popen模塊 os.popen("ls -hl") 執(zhí)行命令,之后通過.read()方法獲取output返回值 subprocess模塊 subprocess.getstatusoutput("ls -hl") 執(zhí)行命令,并返回狀態(tài)status、輸出output subprocess.getoutput("ls -hl") 執(zhí)行命令,只返回輸出結(jié)果output subprocess.call("ls -hl") 執(zhí)行命令并返回狀態(tài)碼 和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) # 執(zhí)行命令,并返回狀態(tài)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')
以上內(nèi)容就是本文的全部敘述,希望大家喜歡。
相關(guān)文章
python 中的divmod數(shù)字處理函數(shù)淺析
這篇文章主要介紹了python divmod數(shù)字處理函數(shù)的相關(guān)資料,感興趣的朋友一起看看吧2017-10-10python中subprocess批量執(zhí)行l(wèi)inux命令
本篇文章給大家詳細講述了python中使用subprocess批量執(zhí)行l(wèi)inux命令的方法,有興趣的朋友參考學(xué)習(xí)下。2018-04-04解決python cv2.imread 讀取中文路徑的圖片返回為None的問題
這篇文章主要介紹了解決python cv2.imread 讀取中文路徑的圖片返回為None的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06