导航:首页 > 编程语言 > python编写守护进程

python编写守护进程

发布时间:2022-07-05 03:23:59

‘壹’ ubuntu python怎么作为守护进程一直运行

测试程序
先写一个测试程序,用于输出日志和打印到控制台。
#-*- coding: utf-8 -*-
import logging
import time
from logging.handlers import RotatingFileHandler

def func():
init_log()
while True:
print "output to the console"
logging.debug("output the debug log")
logging.info("output the info log")
time.sleep(3);

def init_log():
logging.getLogger().setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
console.setFormatter(formatter)
logging.getLogger().addHandler(console)

# add log ratate
Rthandler = RotatingFileHandler("backend_run.log", maxBytes=10 * 1024 * 1024, backupCount=100,
encoding="gbk")
Rthandler.setLevel(logging.INFO)
# formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
Rthandler.setFormatter(formatter)
logging.getLogger().addHandler(Rthandler)

if __name__ == '__main__':
func()

后台启动Python脚本
可以使用下面的命令来启动上面的脚本,让Python在后台运行。
nohup python -u main.py > test.out 2>&1 &

来解释一下这几个命令的参数。这一段来自
其中 0、1、2分别代表如下含义:
0 – stdin (standard input)
1 – stdout (standard output)
2 – stderr (standard error)
nohup python -u main.py > test.out 2>&1 &
nohup+最后面的& 是让命令在后台执行
>out.log 是将信息输出到out.log日志中
2>&1 是将标准错误信息转变成标准输出,这样就可以将错误信息输出到out.log 日志里面来。

运行命令后,会返回一个pid。像下面这样:
[1] 9208

后续可以学习Hadoop它们,把pid存起来,到时候stop的时候就把它杀掉。
跟踪输出文件变化
为了验证脚本可以在后台继续运行,我们退出当前会话。然后重新连接一个Session,然后输入下面的命令来跟踪文件的输出:
tail -f test.out

输出内容如下:
output to the console
2017-03-21 20:15:02,632 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:02,632 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:05,635 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:05,636 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:08,637 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:08,638 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:11,640 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:11,642 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:14,647 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:14,647 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:17,653 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:17,654 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:20,655 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:20,656 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:23,661 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:23,661 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:26,665 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:26,666 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:29,670 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:29,671 main.py[line:12] INFO output the info log

说明我们的脚本确实在后台持续运行。
结束程序
可以直接通过之前的那个pid杀掉脚本,或者可以通过下面的命令查找pid。
ps -ef | grep python

输出的内容如下:
root 1659 1 0 17:40 ? 00:00:00 /usr/bin/python /usr/lib/python2.6/site-packages/ambari_agent/AmbariAgent.py start
root 1921 1659 0 17:40 ? 00:00:48 /usr/bin/python /usr/lib/python2.6/site-packages/ambari_agent/main.py start
user 8866 8187 0 20:03 ? 00:00:06 /usr/bin/python3 /usr/bin/update-manager --no-update --no-focus-on-map
root 9208 8132 0 20:12 pts/16 00:00:00 python -u main.py
root 9358 8132 0 20:17 pts/16 00:00:00 grep --color=auto python

可以看到我们的pid是9208,调用kill杀掉就可以了。
kill -9 9208

编写启动及停止脚本
启动脚本
#!/bin/sh

pid=`ps -ef|grep "python -u main.py"| grep -v "grep"|awk '{print $2}'`

if [ "$pid" != "" ]
then
echo "main.py already run, stop it first"
kill -9 ${pid}
fi

echo "starting now..."

nohup python -u main.py > test.out 2>&1 &

pid=`ps -ef|grep "python -u main.py"| grep -v "grep"|awk '{print $2}'`

echo ${pid} > pid.out
echo "main.py started at pid: "${pid}

停止脚本
#!/bin/sh

pid=`ps -ef|grep "python -u main.py"| grep -v "grep"|awk '{print $2}'`

if [ "$pid" != "" ]
then
kill -9 ${pid}
echo "stop main.py complete"
else
echo "main.py is not run, there's no need to stop it"
fi

稍后我会把实例代码上传到资料共享里面。

‘贰’ 如何给脚本写一个守护进程

在我们日常运维中,写脚本监控一个进程是比较常见的操作,比如我要监控mysql进程是否消失,如果消失就重启mysql,用下面这段代码就可以实现:

#!/bin/sh

Date=` date '+%c'`

while :
do
if ! psaux | grep -w mysqld | grep -v grep >/dev/null 2>&1
then
/etc/init.d/mysqldstart
echo $Datemysqldwasreboot >>/var/log/reboot_mysql.log
fi
done

本篇这是以mysql为例子,但实际中如果是监控的脚本出了问题,报警没发出来,那就比较尴尬了,所以为保证我们的检查脚本能实时运行,我们需要一个进程来守护这个脚本,这就是我们今天要说的主题,如何给脚本写一个daemon,我们先上代码:

#!/usr/bin/python

import subprocess
from daemonimport runner

cmd = "/root/demo_script/restart_mysql.sh"

class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/tmp/hello.pid'
self.pidfile_timeout = 5
def start_subprocess(self):
return subprocess.Popen(cmd, shell=True)
def run(self):
p = self.start_subprocess()
while True:
res = p.poll()
if resis not None:
p = self.start_subprocess()

if __name__ == '__main__':
app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

脚本比较简单,没什么特别的逻辑,关于daemon这个模块如何使用,我这里给出官方的解释,注意哟,是英文的,我就不翻译了,如果有生词就查查字典,就当多学几个了单词吧。

__init__(self, app)
| Setuptheparametersof a new runner.
|
| The `app` :
|
| * `stdin_path`, `stdout_path`, `stderr_path`: Filesystem
| pathsto openand replacetheexisting `sys.stdin`,
| `sys.stdout`, `sys.stderr`.
|
| * `pidfile_path`: Absolutefilesystempathto a filethat
| willbeusedas thePIDfilefor thedaemon. If
| ``None``, noPIDfilewillbeused.
|
| * `pidfile_timeout`: Usedas thedefault acquisition
| timeoutvaluesuppliedto therunner's PIDlockfile.
|
| * `run`:
| started.
|
| do_action(self)
| Performtherequestedaction.
|
| parse_args(self, argv=None)
| Parsecommand-linearguments.

这样就完成了,守护进程的启动比较高大上,输入以上代码后,可以直接在终端输入:

#python monitor.py start

当然还有stop,restart等参数。

这里我介绍的是其中一个应用场景,实际中可以灵活运用,比如1台服务器上启动的程序过多,环境配置比较复杂,就可以先启动daemon进程,然后通过daemon来启动其它所有应用程序,就不用一个一个应用程序启动了,这篇就到这里,有问题可以给我留言。

‘叁’ 如何把 python predict程序 做成 windows 守护进程

importos,sys,commands,time

defdaemonize(stdin='/dev/null',stdout='/dev/null',stderr='/dev/null'):
"""setdaemonize"""
try:
pid=os.fork()
ifpid>0:
sys.exit(0)
exceptOSError,e:
sys.stderr.write("fork#1failed(%d)%s "%(e.errno,e.strerror))
sys.exit(0)

os.setsid()
os.chdir('.')
os.umask(0)

try:
pid=os.fork()
ifpid>0:
sys.exit(0)
exceptOSError,e:
sys.stderr.write("fork#2failed(%d)%s "%(e.errno,e.strerror))
sys.exit(0)

ifnotstderr:stderr=stdout
si=file(stdin,"r")
so=file(stdout,"w+")
se=file(stderr,"a+")
pid=str(os.getpid())
print"startwithpid:[%s]"%pid
fp=open("pid","w")
print>>fp,pid
fp.close()
sys.stderr.flush()

sys.stdout.flush()
sys.stderr.flush()
os.p2(si.fileno(),sys.stdin.fileno())
os.p2(so.fileno(),sys.stdout.fileno())
os.p2(se.fileno(),sys.stderr.fileno())

defmain():
daemonize(stdout='test.log',stderr='test.log')

cmd="ls"
while1:
(status,ret)=commands.getstatusoutput(cmd)
printstatus
printret
time.sleep(10)

if__name__=="__main__":
main()

你可以尝试照这个写写,基本的元素都齐了,后台运行,执行shell命令
不过如果只是想要后台的话,直接shell后台执行一下也就可以了

‘肆’ 如何把crontab的时间触发用python来实现守护进程控制

既然要用python来控制,为什么还要crontab呢?直接通过python调用相应的命令执行 不就可以了么?

‘伍’ 如何用python编写一个程序,在服务器后台运行,每天删除一些文件

首先利用

os.remove() will remove a file.
os.rmdir() will remove an empty directory.
shutil.rmtree() will delete a directory and all its contents.
写你的模块
利用Linux crontab定时任务运行这个模块。
还可以以守护进程的方式运行你的脚本。nohup <程序名> &

‘陆’ 如何使用Python守护进程和脚本

项目过程中,经常会有很多的脚本,Shell脚本、PHP脚本、Python脚本等,更有一些脚本是需要常驻内存执行的,简而言之就是需要while(true){}的模式执行。
但是有的时候,一个常驻内存的进程会因为某些耗时操作而夯住,不再往下继续执行,成为了一个僵尸进程;或者因为某个操作偶然出错,直接退出了;
所以我们需要有一套简单的机制来保证进程一直处于活跃状态。

‘柒’ 如何在python脚本中新建一个守护子进程

函数实现
[html] view plain
#!/usr/bin/env python
#coding: utf-8
import sys, os

'''将当前进程fork为一个守护进程
注意:如果你的守护进程是由inetd启动的,不要这样做!inetd完成了
所有需要做的事情,包括重定向标准文件描述符,需要做的事情只有chdir()和umask()了
'''

def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
#重定向标准文件描述符(默认情况下定向到/dev/null)
try:
pid = os.fork()
#父进程(会话组头领进程)退出,这意味着一个非会话组头领进程永远不能重新获得控制终端。
if pid > 0:
sys.exit(0) #父进程退出
except OSError, e:
sys.stderr.write ("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) )
sys.exit(1)

#从母体环境脱离
os.chdir("/") #chdir确认进程不保持任何目录于使用状态,否则不能umount一个文件系统。也可以改变到对于守护程序运行重要的文件所在目录
os.umask(0) #调用umask(0)以便拥有对于写的任何东西的完全控制,因为有时不知道继承了什么样的umask。
os.setsid() #setsid调用成功后,进程成为新的会话组长和新的进程组长,并与原来的登录会话和进程组脱离。

#执行第二次fork
try:
pid = os.fork()
if pid > 0:
sys.exit(0) #第二个父进程退出
except OSError, e:
sys.stderr.write ("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror) )
sys.exit(1)

#进程已经是守护进程了,重定向标准文件描述符

for f in sys.stdout, sys.stderr: f.flush()
si = open(stdin, 'r')
so = open(stdout, 'a+')
se = open(stderr, 'a+', 0)
os.p2(si.fileno(), sys.stdin.fileno()) #p2函数原子化关闭和复制文件描述符
os.p2(so.fileno(), sys.stdout.fileno())
os.p2(se.fileno(), sys.stderr.fileno())

#示例函数:每秒打印一个数字和时间戳
def main():
import time
sys.stdout.write('Daemon started with pid %d\n' % os.getpid())
sys.stdout.write('Daemon stdout output\n')
sys.stderr.write('Daemon stderr output\n')
c = 0
while True:
sys.stdout.write('%d: %s\n' %(c, time.ctime()))
sys.stdout.flush()
c = c+1
time.sleep(1)

if __name__ == "__main__":
daemonize('/dev/null','/tmp/daemon_stdout.log','/tmp/daemon_error.log')
main()
可以通过命令ps -ef | grep daemon.py查看后台运行的继承,在/tmp/daemon_error.log会记录错误运行日志,在/tmp/daemon_stdout.log会记录标准输出日志。

‘捌’ Linux下的守护进程的概念daemon.py是什么意思

守护进程一般是服务器类程序中用来无限循环等待事件发生的一个进程或线程,也就是说,它的作用是等待一个事件发生,事件发生后调用另外的进程区完成相应的工作,自己再回去等事件发生。
用ps aux查看进程的进程号,然后用kill杀掉
py是后缀名,意思是用python语言写的。
至于如何重启,这个没有统一的方法。你可以查看相关的文档,或者在google上搜索,或者man一下。。
守护进程一个或者多个都是可能的。

‘玖’ 如何使用Python的Supervisor来管理进程

在python开发中,如何使用supervisor来管理进程呢?Supervisor是什么?Supervisor是如何管理进程的,现在就跟随小编一起来看看使用python的supervisor管理经常的方法。
Supervisor可以启动、停止、重启*nix系统中的程序。也可以重启崩溃的程序。
supervisord的一个守护进程,用于将指定的进程当做子进程来运行。
supervisorctl是一个客户端程序,可以查看日志并通过统一的会话来控制进程。
看例子:
我们写了一个py脚本,用于往log文件中记录一条当前的时间。
[python]view plain
1.root@ubuntu:/home/zoer#catdaemon.py
2.#!/usr/bin/envpython
3.
4.importtime
5.importos
6.time.sleep(1)
7.f=open("log",'a')
8.t=time.time()
9.f.write(str(t))
10.f.write("\n")
11.f.close()
安装过程就不说了。
安装完毕supervisor之后【将配置文件放在/etc下】。修改配置文件,在最后增加如下内容:
[program:ddd]
command=/home/zoer/daemon.py
autorestart=true
然后我们启动supervisor并启动daemon.py的执行。
[python]view plain
1.root@ubuntu:/home/zoer#supervisord
2./usr/local/lib/python2.7/dist-packages/supervisor-3.0b1-py2.7.egg/supervisor/options.py:286:UserWarning:aultlocations();youprobablywanttospecifya"-c"y.
3.''
4.root@ubuntu:/home/zoer#supervisorctl
5.dddSTARTING
6.supervisor>startddd
7.ddd:ERROR(alreadystarted)
8.supervisor>stopddd
9.ddd:stopped
10.supervisor>startddd
11.ddd:started
12.supervisor>
从上面的例子中,看到,可以通过start或者stop命令来启动或者停止ddd这个进程。ddd这里就是我们在配置文件中增加的内容(daemon.py这个脚本)。
也可以使用restart。如下:
supervisor> restart ddd
ddd: stopped
ddd: started
-------------------------------------------------------
下面我们测试一下,假设说我们手动kill掉了ddd这个进程,那么ddd会自动恢复执行吗?
为了做实验,把代码修改如下:
[python]view plain
1.root@ubuntu:/home/zoer#catdaemon.py
2.#!/usr/bin/envpython
3.
4.importtime
5.importos
6.whileTrue:
7.time.sleep(1)
8.f=open("log",'a')
9.t=time.time()
10.f.write(str(t))
11.f.write("\n")
12.f.close()
通过ps可以找到这个进程的id:
[plain]view plain
1.root93540.20.4109244200?S23:160:00python/home/zoer/daemon.py
2.root93950.00.04392832pts/3S+23:170:00grep--color=autodaemon
3.root@ubuntu:/home/zoer#
看下面的操作:
[plain]view plain
1.root@ubuntu:/home/zoer#rmlog;touchlog;kill9354
2.root@ubuntu:/home/zoer#catlog
3.1364710712.51
4.root@ubuntu:/home/zoer#catlog
5.1364710712.51
6.1364710713.51
7.root@ubuntu:/home/zoer#catlog
8.1364710712.51
9.1364710713.51
10.root@ubuntu:/home/zoer#catlog
11.1364710712.51
12.1364710713.51
13.1364710714.52
14.root@ubuntu:/home/zoer#catlog
15.1364710712.51
16.1364710713.51
17.1364710714.52
18.1364710715.52
删除了log文件,并且重新创建。然后干掉了daemon.py的那个进程。会发现log内容又重新有新的内容了。再次ps查看进程号。
[plain]view plain
1.root94290.10.4109244200?S23:180:00python/home/zoer/daemon.py
2.root94400.00.04392828pts/3S+23:190:00grep--color=autodaemon
3.root@ubuntu:/home/zoer#
会发现进程号已经变成9429了。说明supervisor已经重启了被干掉了的进程。

‘拾’ python 怎么设置守护进程

thread[i].join()
用join()方法去设置守护线程。
不过此方法只在threading中才有。

阅读全文

与python编写守护进程相关的资料

热点内容
编译程序输入一个字符串 浏览:402
圆命令画法 浏览:303
如果给电脑e盘文件加密 浏览:801
javaswing项目 浏览:774
androidsdksetup 浏览:1003
pdf怎么设置中文 浏览:126
安卓手机用什么软件看伦敦金 浏览:962
魅族文件夹无名称 浏览:789
苏黎世无人机算法 浏览:872
核桃编程和小码王的融资 浏览:684
微积分教材pdf 浏览:725
写python给微信好友发消息 浏览:336
蚊帐自营米加密 浏览:418
学校推荐核桃编程 浏览:804
湖南农信app怎么导明细 浏览:471
福特abs编程 浏览:509
如何自学安卓手机 浏览:439
以太坊源码共识机制 浏览:910
单片机探测器 浏览:872
demo编程大赛作品怎么运行 浏览:52