程序意外中斷自動重啓shell腳本(以樹莓派運行Python爲例)

程序意外中斷自動重啓shell腳本(以樹莓派運行Python爲例)

我們經常需要在後臺運行一些python腳本,來監控系統或者做一些其他事情;但是 由於各種各樣的原因,排除python腳本代碼的問題,腳本運行過程中會掛掉。爲了不天天耗在上面等重啓,可以製作shell腳本對程序予以監控,對於意外中斷的程序自動重啓。

以控制 python自動重啓的shell腳本爲例:

cd Desktop
vim run.sh  #新建名爲run的shell腳本

寫入(此處以名爲run的Python腳本爲例)

#!/bin/bash
while [ 1 ];do
    python run.py
done
chmod 777 run.sh    #設置shell腳本權限
./run.sh            #運行shell腳本

在這裏插入圖片描述
在這裏插入圖片描述
可見Python腳本意外中斷(被kill)後,由於shell腳本的循環語句,實現了自動重啓。
在這裏插入圖片描述
在測試完確保能夠正常運行後,切換爲後臺運行:關於後臺運行命令原理,點此查看

nohup ./run5.py &

在這裏插入圖片描述


此外,做爬蟲項目時,我們需要考慮一個爬蟲在爬取時會遇到各種情況(網站驗證,ip封禁),導致爬蟲程序中斷,這時我們已經爬取過一些數據,再次爬取時這些數據就可以忽略,所以我們需要在爬蟲項目中設置一箇中斷重連的功能,使其在重新運行時從之前斷掉的位置重新爬取數據。此代碼參見自 匡虐博客

import os
class UrlManager(object):
    def __init__(self):						#建立兩個數組的文件
        with open('new_urls.txt','r+') as new_urls:
            self.new_urls = new_urls.read()
        with open('old_urls.txt','r+') as old_urls:
            self.old_urls = old_urls.read()

    def add_new_url(self, url): 				 #添加url到new_ulrs文件中
        if url is None:
            return
        if url not in self.new_urls and url not in self.old_urls:
            with open('new_urls.txt', 'a') as new_urls:
                new_urls.write(url)
        else:
            print('url had done')

    def add_new_urls(self, urls):				#添加多個url到new_ulrs文件中
        # if urls is None or (len(url) == 0 for url in urls):
        if urls is None:
            print('url is none')
            return
        for url in urls:
            if urls is None:
                print('url is none')
                return
            else:
                self.add_new_url(url)

    def has_new_url(self):
        return len(self.new_urls) != 0

    def get_new_url(self):				
        new_url = get_last_line('new_urls.txt')   	#讀取new_urls文件中最後一個url
        del_last_url('new_urls.txt',new_url)		#刪除new_urls文件中最後一個url
        add_old_urls('old_urls.txt',new_url)		#將讀取出來的url添加入old_urls數組中
        return new_url

	def get_last_line(inputfile):
	    filesize = os.path.getsize(inputfile)
	    blocksize = 1024
	    dat_file = open(inputfile, 'rb')
	
	    last_line = b""
	    lines = []
	    if filesize > blocksize:
	        maxseekpoint = (filesize // blocksize)  # 這裏的除法取的是floor
	        maxseekpoint -= 1
	        dat_file.seek(maxseekpoint * blocksize)
	        lines = dat_file.readlines()
	        while ((len(lines) < 2) | ((len(lines) >= 2) & (lines[1] == b'\r\n'))):  # 因爲在Windows下,所以是b'\r\n'
	            # 如果列表長度小於2,或者雖然長度大於等於2,但第二個元素卻還是空行
	            # 如果跳出循環,那麼lines長度大於等於2,且第二個元素肯定是完整的行
	            maxseekpoint -= 1
	            dat_file.seek(maxseekpoint * blocksize)
	            lines = dat_file.readlines()
	    elif filesize:  # 文件大小不爲空
	        dat_file.seek(0, 0)
	        lines = dat_file.readlines()
	    if lines:  # 列表不爲空
	        for i in range(len(lines) - 1, -1, -1):
	            last_line = lines[i].strip()
	            if (last_line != b''):
	                break  # 已經找到最後一個不是空行的
	    dat_file.close()
	    return last_line
	
	def del_last_url(fname,part):
	    with open(fname,'rb+') as f:
	        a = f.read()
	    a = a.replace(part,b'')
	    with open(fname,'wb+') as f:
	        f.write(a)
	        
	def add_old_urls(fname,new_url):
	    line = new_url + b'\r'
	    with open(fname,'ab') as f:
	        f.write(line)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章