日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python模块——subprocess

發布時間:2023/11/29 python 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python模块——subprocess 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

subprocess模塊

通過Python去執行一條系統命令或腳本。

三種執行命令的方法

  • subprocess.run(*popenargs, input=None, timeout=None, check=False, **kwargs) #官方推薦

  • subprocess.call(*popenargs, timeout=None, **kwargs) #跟上面實現的內容差不多,另一種寫法

  • subprocess.Popen() #上面各種方法的底層封裝

run方法

標準寫法

subprocess.run(['df','-h'],stderr=subprocess.PIPE,stdout=subprocess.PIPE,check=True) #check=True代表,如果命令出現錯誤,程序會拋出異常

涉及到管道|的命令需要這樣寫

subprocess.run('df -h|grep disk1',shell=True) #shell=True的意思是這條命令直接交給系統去執行,不需要python負責解析

?

call方法

#執行命令,返回命令執行狀態 , 0 or 非0 >>> 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'

Popen方法

常用參數:

  • args:shell命令,可以是字符串或者序列類型(如:list,元組)
  • stdin, stdout, stderr:分別表示程序的標準輸入、輸出、錯誤句柄
  • preexec_fn:只在Unix平臺下有效,用于指定一個可執行對象(callable object),它將在子進程運行之前被調用
  • shell:同上
  • cwd:用于設置子進程的當前目錄
  • env:用于指定子進程的環境變量。如果env = None,子進程的環境變量將從父進程中繼承。

下面這2條語句執行會有什么區別?

a=subprocess.run('sleep 10',shell=True,stdout=subprocess.PIPE) a=subprocess.Popen('sleep 10',shell=True,stdout=subprocess.PIPE)

區別是Popen會在發起命令后立刻返回,而不等命令執行結果。這樣的好處是什么呢?

如果你調用的命令或腳本 需要執行10分鐘,你的主程序不需卡在這里等10分鐘,可以繼續往下走,干別的事情,每過一會,通過一個什么方法來檢測一下命令是否執行完成就好了。

Popen調用后會返回一個對象,可以通過這個對象拿到命令執行結果或狀態等,該對象有以下方法

poll()Check if child process has terminated. Returns returncodewait()Wait for child process to terminate. Returns returncode attribute.terminate()終止所啟動的進程Terminate the process with SIGTERMkill() 殺死所啟動的進程 Kill the process with SIGKILL
send_signal(signal.xxx)發送系統信號pid 拿到所啟動進程的進程號

?poll

>>> a=subprocess.Popen('sleep 10',shell=True,stdout=subprocess.PIPE) >>> a.poll() >>> a.poll() >>> a.poll() 0

?termiate

>>> a = subprocess.Popen('for i in $(seq 1 100);do sleep 1;echo $i >> /tmp/sleep.log;done',shell=True, cwd='/tmp',stdout=subprocess.PIPE) >>> a.terminate() >>>

?

preexec_fn

>>> def sayhi(): ... print('haha') ... >>> a = subprocess.Popen('sleep 5',shell=True,stdout=subprocess.PIPE,preexec_fn=sayhi) >>> a.stdout <_io.BufferedReader name=3> >>> a.stdout.read() b'haha\n' >>> a.pid 2070

?

代碼案例

import subprocess from utils import unicode_utils # 執行cmd或shell命令# from multiprocessing.dummy import Pool as ThreadPooldef cmd_exec(cmd):"""執行shell命令返回命令返回值和結果:param cmd::return:"""p = subprocess.Popen(cmd,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)stdout, stderr = p.communicate()#從PIPE中讀取出PIPE中的文本,放入內存if p.returncode != 0:return {'code':p.returncode, 'res':unicode_utils.to_str(stderr)}return {'code':p.returncode, 'res':unicode_utils.to_str(stdout)}if __name__ == '__main__':passcmd_list =[]cmd_list.append('df -h')cmd_list.append('ps -ef|grep jav1a|grep -v grep')cmd_list.append('ps -ef|grep "pol"')cmd_list.append('sh /root/ops/sum.sh')# print(cmd_exec(cmd))# Make the Pool of workerspool = ThreadPool(4)# Open the urls in their own threads# and return the resultsresults = pool.map(cmd_exec, cmd_list)# close the pool and wait for the work to finishprint(results)pool.close()pool.join()************************************** unicode_utils:def to_str(bytes_or_str):"""把byte類型轉換為str:param bytes_or_str::return:"""if isinstance(bytes_or_str, bytes):value = bytes_or_str.decode('utf-8')else:value = bytes_or_strreturn value

  

  

?

轉載于:https://www.cnblogs.com/xiao-apple36/p/8857201.html

總結

以上是生活随笔為你收集整理的Python模块——subprocess的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。