python程序运行方式几种_Python脚本后台运行的几种方式

这篇文章主要介绍了

Python

脚本后台运行的几种方式

,linux

下后台运行、通过

upstart

方式实现、通过

bash

脚本实现、通过

screen

tmux

等方式实现

,

需要的朋友可以参考下

一个用

python

写的监控脚本

test1.py

,用

while

True

方式一直运行,在

ssh

远程(使用

putty

终端)时通过以下命令启动脚本:

代码如下

:

python test1.py &

现在脚本正常运行,通过

ps

能看到进程号,此时直接关闭

ssh

终端(不是用

exit

命令,

是直接通过

putty

的关闭按钮执行的)

再次登录后发现进程已经退出了。

通过后台启动的方式该问题已经解决,这里总结下,也方便我以后查阅。

linux

下后台运行

通过

fork

实现

linux

环境下,

c

中守护进程是通过

fork

方式实现的,

python

也可以通过该方式实现,

示例代码如下:

代码如下

:

#!/usr/bin/env python

import time,platform

import os

def funzioneDemo():

#

这是具体业务函数示例

fout = open('/tmp/demone.log', 'w')

while True:

fout.write(time.ctime()+'\n')

fout.flush()

time.sleep(2)

fout.close()

def createDaemon():

# fork

进程

try:

if os.fork() > 0: os._exit(0)

except OSError, error:

print 'fork #1 failed: %d (%s)' % (error.errno, error.strerror)

os._exit(1)

os.chdir('/')

os.setsid()

os.umask(0)

try:

pid = os.fork()

if pid > 0:

print 'Daemon PID %d' % pid

os._exit(0)

except OSError, error:

print 'fork #2 failed: %d (%s)' % (error.errno, error.strerror)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值