twisted 使用application框架制作守护进程

2023-10-18 19:20

本文主要是介绍twisted 使用application框架制作守护进程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

官方文档

http://twistedmatrix.com/documents/12.2.0/core/howto/application.html

起由:

       用twisted写了一个程序,只能像脚本一样运行,ctrl+c 就退出了,如果用screen 或者nohup都有一些问题,查了一下twsited自带daemon应用框架,于是赶紧google了一下(顺便提一下,没有抗争就没有自由,目前还可以用的google镜像地址:https://s3-ap-southeast-1.amazonaws.com/google.cn/index.html),现在做一点笔记,方便下次查阅。

可以有多种方式实现守护进程,这里介绍2种:

第一种:非插件式的

原文的概念有点难啃,我喜欢画个图来加深下自己的理解。


下面贴一段自己的代码

from twisted.internet import reactor
from twisted.internet.protocol import ServerFactory
from twisted.protocols import basic
import cx_Oracle
from twisted.application import  service, internetclass Mornitor_Protocol(basic.LineReceiver):def __init__(self):#不知道要写什么_oracle_conn=cx_Oracle.connect('xxx', 'xxx', '192.168.7.17/test', threaded=True)_oracle_conn.autocommit = Trueself.cur = _oracle_conn.cursor()self._oracle_conn=_oracle_conndef ruku(self, line):ip = self.transport.getPeer().host#获取客户端IPline=line.split(':::')#使用:::分割原始数据if line[1] in ['cpu', 'mem', 'disk', 'tcp', 'net', 'process_down']:#根据数据包头来确定使用insert还是update,当是tcp包头的时候插入,其余的更新if line[1] == 'tcp':sql = "insert into MORNITOR_BASICINFO (ipadd,time,tcp) values (\'%s\',\'%s\',\'%s\')"%(ip,line[0],line[3])print sqlself.cur.execute(sql)else:line_again = line[3].split('::')sql = 'update MORNITOR_BASICINFO set %s=\'%s\',%s=\'%s\' where ipadd=\'%s\' and time=\'%s\''%(line[1],line_again[0],line[2],line_again[1],ip,line[0])print sqlself.cur.execute(sql)def connectionMade(self):print 'Connected!'def lineReceived(self, line):print lineself.ruku(line)#接受到数据之后执行入库操作!def connectionLost(self, reason='connectionDone'):self._oracle_conn.close()print 'The db is close... ok!'class Mornitor_Factory(ServerFactory):#还没想好要初始化什么protocol = Mornitor_Protocoldef __init__(self,service):self.service = serviceclass Fish_Service(service.Service):def startService(self):service.Service.startService(self)def stopService(self):return self._port.stopListening()port = 8888
iface = '192.168.7.188'top_service = service.MultiService()fish_server =Fish_Service()
factory = Mornitor_Factory(Fish_Service)
fish_server.setServiceParent(top_service)tcp_service = internet.TCPServer(port, factory, interface=iface)
tcp_service.setServiceParent(top_service)application = service.Application("SmallFish--Monitor")# this hooks the collection we made to the application
top_service.setServiceParent(application)

使用 twisted -y main.py (脚本名称) 就可以以守护进程的方式运行了!

第二种:插件式

何谓插件式?

举个例子就是不敲任何参数,直接在命令行打twisted后,可以看到的一些插件,如下:

dwj@WaitFish ~ $ twistd twistd reads a twisted.application.service.Application out of a file and runs
it.
Commands:conch            A Conch SSH service.dns              A domain name server.ftp              An FTP server.inetd            An inetd(8) replacement.mail             An email servicemanhole          An interactive remote debugger service accessible viatelnet and ssh and providing syntax coloring and basic lineediting functionality.manhole-old      An interactive remote debugger service.news             A news server.portforward      A simple port-forwarder.procmon          A process watchdog / supervisorsocks            A SOCKSv4 proxy service.telnet           A simple, telnet-based remote debugging service.web              A general-purpose web server which can serve from afilesystem or application resource.words            A modern words serverxmpp-router      An XMPP Router server

略去usage 就是上面的输出,其中twisted自带的插件有常见的一些协议如ftp mail news web telnet等等~~

如果能将自己的应用程序注册成插件岂不是一件很爽快的事情。

以下是插件结构IServiceMaker指定了三个属性和一个方法:(转载自https://github.com/luocheng/twisted-intro-cn/blob/master/p16.rst#iservicecollection)

  1. tapname: 代表插件名字的字符串. "tap"代表"Twisted Application Plugin". 注:老版本的Twisted还使用"tapfiles"文件,不过这个功能现在已经取消了.
  2. description: 插件的描述, twistd 将以它作为帮助信息输出.
  3. options: 一个代表这个插件接受的命令行选项的对象.
  4. makeService: 一个创建 IService 对象的方法,需提供一些特定的命令行选项.
这些参数有什么作用,以及要怎么样去理解呢,大体上就是把刚才从service->muti-service->appliaction的过程柔和成makeService+options


继续贴上刚才的代码用插件来实现:

from twisted.internet import reactor
from twisted.internet.protocol import ServerFactory
from twisted.protocols import basic
import cx_Oracle
from twisted.application import  service, internet
from zope.interface import implements
from twisted.python import usage, log
from twisted.plugin import IPluginclass Mornitor_Protocol(basic.LineReceiver):def __init__(self):#不知道要写什么_oracle_conn=cx_Oracle.connect('xxx', 'xxx', '192.168.7.17/test', threaded=True)_oracle_conn.autocommit = Trueself.cur = _oracle_conn.cursor()self._oracle_conn=_oracle_conndef ruku(self, line):ip=self.transport.getPeer().host#获取客户端IPline=line.split(':::')#使用:::分割原始数据if line[1] in ['cpu', 'mem', 'disk', 'tcp', 'net', 'process_down']:#根据数据包头来确定使用insert还是update,当是tcp包头的时候插入,其余的更新if line[1] == 'tcp':sql = "insert into MORNITOR_BASICINFO (ipadd,time,tcp) values (\'%s\',\'%s\',\'%s\')"%(ip,line[0],line[3])print sqlself.cur.execute(sql)else:line_again = line[3].split('::')sql = 'update MORNITOR_BASICINFO set %s=\'%s\',%s=\'%s\' where ipadd=\'%s\' and time=\'%s\''%(line[1],line_again[0],line[2],line_again[1],ip,line[0])print sqlself.cur.execute(sql)def connectionMade(self):print 'Connected!'def lineReceived(self, line):print lineself.ruku(line)#接受到数据之后执行入库操作!def connectionLost(self, reason='connectionDone'):self._oracle_conn.close()print 'The db is close... ok!'class Mornitor_Factory(ServerFactory):#还没想好要初始化什么def __init__(self, s):self.service = sprotocol = Mornitor_Protocolclass Fish_Service(service.Service):def __init__(self):self._port=8007def startService(self):service.Service.startService(self)class Options(usage.Options):optParameters = [['port', 'p', 10000, 'The port number to listen on.'],['iface', None, 'localhost', 'The interface to listen on.'],]class Fish_Service_Make(object):implements(service.IServiceMaker, IPlugin)tapname = "smallfish"                  #这里给插件取个好听的名字description = "A monitor daemon!"      #插件的描述options = Options                      #可供插件选择的选项def makeService(self, options):top_service = service.MultiService()                  #定义service容器fish_service = Fish_Service()                         #实例化自己定义的servicefish_service.setServiceParent(top_service)            #把自定义的service丢进容器factory = Mornitor_Factory(fish_service)              #工厂化自定义服务tcp_service = internet.TCPServer(int(options['port']), factory,           #tcp连接工厂化,一些连接参数通过option获取interface=options['iface'])tcp_service.setServiceParent(top_service)             #把tcp sevice丢进容器​        return top_serviceservice_maker = Fish_Service_Make()        

要使用twisted +插件名称的方式运行程序有几点要求:

1.插件程序必须在python的搜索路径


export PYTHONPATH=$PYTHONPATH:/home/user/yourpath

2.插件程序必须处于twisted/plugins 这样的目录结构下

your projects/
├──
twisted
└── plugins
    └──xxxx_plugin.py

这篇关于twisted 使用application框架制作守护进程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/234641

相关文章

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

pdfmake生成pdf的使用

实际项目中有时会有根据填写的表单数据或者其他格式的数据,将数据自动填充到pdf文件中根据固定模板生成pdf文件的需求 文章目录 利用pdfmake生成pdf文件1.下载安装pdfmake第三方包2.封装生成pdf文件的共用配置3.生成pdf文件的文件模板内容4.调用方法生成pdf 利用pdfmake生成pdf文件 1.下载安装pdfmake第三方包 npm i pdfma

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

git使用的说明总结

Git使用说明 下载安装(下载地址) macOS: Git - Downloading macOS Windows: Git - Downloading Windows Linux/Unix: Git (git-scm.com) 创建新仓库 本地创建新仓库:创建新文件夹,进入文件夹目录,执行指令 git init ,用以创建新的git 克隆仓库 执行指令用以创建一个本地仓库的

【北交大信息所AI-Max2】使用方法

BJTU信息所集群AI_MAX2使用方法 使用的前提是预约到相应的算力卡,拥有登录权限的账号密码,一般为导师组共用一个。 有浏览器、ssh工具就可以。 1.新建集群Terminal 浏览器登陆10.126.62.75 (如果是1集群把75改成66) 交互式开发 执行器选Terminal 密码随便设一个(需记住) 工作空间:私有数据、全部文件 加速器选GeForce_RTX_2080_Ti

cross-plateform 跨平台应用程序-03-如果只选择一个框架,应该选择哪一个?

跨平台系列 cross-plateform 跨平台应用程序-01-概览 cross-plateform 跨平台应用程序-02-有哪些主流技术栈? cross-plateform 跨平台应用程序-03-如果只选择一个框架,应该选择哪一个? cross-plateform 跨平台应用程序-04-React Native 介绍 cross-plateform 跨平台应用程序-05-Flutte