详解程序意外中断自动重启shell脚本(以Python为例)


Posted in Python onJuly 26, 2019

我们经常需要在后台运行一些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脚本

详解程序意外中断自动重启shell脚本(以Python为例)

详解程序意外中断自动重启shell脚本(以Python为例)

可见Python脚本意外中断(被kill)后,由于shell脚本的循环语句,实现了自动重启。

详解程序意外中断自动重启shell脚本(以Python为例)

在测试完确保能够正常运行后,切换为后台运行:关于后台运行命令原理,点此查看。

nohup ./run5.py &

详解程序意外中断自动重启shell脚本(以Python为例)

此外,做爬虫项目时,我们需要考虑一个爬虫在爬取时会遇到各种情况(网站验证,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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python抓取京东价格分析京东商品价格走势
Jan 09 Python
python编写网页爬虫脚本并实现APScheduler调度
Jul 28 Python
Python中尝试多线程编程的一个简明例子
Apr 07 Python
pandas的object对象转时间对象的方法
Apr 11 Python
python装饰器-限制函数调用次数的方法(10s调用一次)
Apr 21 Python
使用python爬取B站千万级数据
Jun 08 Python
解决python中用matplotlib画多幅图时出现图形部分重叠的问题
Jul 07 Python
python opencv调用笔记本摄像头
Aug 28 Python
python使用Matplotlib改变坐标轴的默认位置
Oct 18 Python
详解用Python爬虫获取百度企业信用中企业基本信息
Jul 02 Python
Python爬虫基于lxml解决数据编码乱码问题
Jul 31 Python
解决Python保存文件名太长OSError: [Errno 36] File name too long
May 11 Python
python的pstuil模块使用方法总结
Jul 26 #Python
python爬虫项目设置一个中断重连的程序的实现
Jul 26 #Python
python通过http下载文件的方法详解
Jul 26 #Python
快速解决vue.js 模板和jinja 模板冲突的问题
Jul 26 #Python
Python调用C语言的实现
Jul 26 #Python
Python实现的企业粉丝抽奖功能示例
Jul 26 #Python
对Django外键关系的描述
Jul 26 #Python
You might like
PHP动态图像的创建
2006/10/09 PHP
限制ckeditor上传图片文件大小的方法
2013/11/15 PHP
Windows Server 2008 R2和2012中PHP连接MySQL过慢的解决方法
2016/07/02 PHP
laravel框架使用FormRequest进行表单验证,验证异常返回JSON操作示例
2020/02/18 PHP
javascript下操作css的float属性的特殊写法
2007/08/22 Javascript
ztree获取当前选中节点子节点id集合的方法
2015/02/12 Javascript
JS动画效果打开、关闭层的实现方法
2015/05/09 Javascript
JQuery选择器、过滤器大整理
2015/05/26 Javascript
node.js缺少mysql模块运行报错的解决方法
2016/11/13 Javascript
php简单数据库操作类的封装
2017/06/08 Javascript
javascript 日期相减-在线教程(附代码)
2017/08/17 Javascript
JavaScript数据结构之优先队列与循环队列实例详解
2017/10/27 Javascript
JavaScript面向对象的程序设计(犯迷糊的小羊)
2018/05/27 Javascript
[02:42]DOTA2英雄基础教程 杰奇洛
2013/12/23 DOTA
[42:06]2019国际邀请赛全明星赛 8.23
2019/09/05 DOTA
Python实现的简单万年历例子分享
2014/04/25 Python
python使用itchat实现手机控制电脑
2018/02/22 Python
python中的文件打开与关闭操作命令介绍
2018/04/26 Python
实践Vim配置python开发环境
2018/07/02 Python
Python绘制KS曲线的实现方法
2018/08/13 Python
python爬虫获取小区经纬度以及结构化地址
2018/12/30 Python
python re库的正则表达式入门学习教程
2019/03/08 Python
python微信聊天机器人改进版(定时或触发抓取天气预报、励志语录等,向好友推送)
2019/04/25 Python
Python利用requests模块下载图片实例代码
2019/08/12 Python
Python List列表对象内置方法实例详解
2019/10/22 Python
Django 设置admin后台表和App(应用)为中文名的操作方法
2020/05/10 Python
Python使用20行代码实现微信聊天机器人
2020/06/05 Python
keras 指定程序在某块卡上训练实例
2020/06/22 Python
解决Keras中循环使用K.ctc_decode内存不释放的问题
2020/06/29 Python
Python创建简单的神经网络实例讲解
2021/01/04 Python
用html5的canvas画布绘制贝塞尔曲线完整代码
2013/08/14 HTML / CSS
护理专科自荐书范文
2014/02/18 职场文书
学习雷锋演讲稿
2014/05/10 职场文书
mybatis 解决从列名到属性名的自动映射失败问题
2021/06/30 Java/Android
spring cloud eureka 服务启动失败的原因分析及解决方法
2022/03/17 Java/Android
Java实现添加条码或二维码到Word文档
2022/06/01 Java/Android