subprocess模塊

```import os ## os.system() #輸出命令結果到屏幕,返回命令的執行狀態 ## os.popen("dir").read #會保存命令的執行結果並輸出 # 在linux裏面 import subprocess subprocess.run(["ipconfig","ping 192.168.1.1"]) #同時執行多條命令 subprocess.run("df -h |grep book",shell=True) #把book文件過濾出來(涉及到管道符直接把字符串傳給真正在調用的shell) ##subprocess模塊常用命令 #執行命令,返回命令執行狀態 , 0 or 非0 和os.sys一樣 retcode = subprocess.call(["ls", "-l"]) #執行命令,如果命令結果爲0,就正常返回,否則拋異常 subprocess.check_call(["ls", "-l"]) 0 ##(必須會用的)接收字符串格式命令,返回元組形式,第1個元素是執行狀態,第2個是命令結果(有執行狀態也有結果) subprocess.getstatusoutput('ls /bin/ls') (0, '/bin/ls') #接收字符串格式命令,並返回結果 subprocess.getoutput('ls /bin/ls') '/bin/ls' #執行命令,並返回結果,注意是返回結果,不是打印,下例結果返回給res res=subprocess.check_output(['ls','-l']) res b'total 0\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\n' ##把結果存在管道里,用stdout讀取 res=subprocess.Popen("ifconfig|grep 192",shell=True,stdout=subprocess.PIPE) res.stdout.read() ##stdout對屏幕的標準輸出 ##stdin 標準輸入 ##stderr 把錯誤單獨分開 res=subprocess.Popen("ifcontttfig|grep 192",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) res.stdout.read() #因爲命令錯誤所以讀取爲空 res.stderr.read() #讀取錯誤信息 # poll() res=subprocess.Popen("slppe 10;echo 'hello'",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) print(res.poll())#輸出none代表命令程序沒有執行完,返回0表示命令程序執行完。 res.wait() #等待命令執行完後返回0 res.terminate() #殺死正在執行程序,讀取程序信息是空 # cwd res=subprocess.Popen("slppe 10;echo 'hello'",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,cwd="/temp") res.stdout.read() #b'/tmp\n'新啓動的shell目錄所在的地方 #sudo自動輸入密碼 echo"123" | sudo -S apt-get install vim #自動輸密碼 subprocess.Popen("echo'123' | sudo -S apt-get install vim",shell=True) #在linux下調用python實現自動輸入密碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章