登录  /  注册
首页 > web前端 > js教程 > 正文

Python脚本后台运行的几种方式

PHP中文网
发布: 2017-04-01 15:15:29
原创
2878人浏览过

一个用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)
        os._exit(1)
    # 重定向标准IO
    sys.stdout.flush()
    sys.stderr.flush()
    si = file("/dev/null", 'r')
    so = file("/dev/null", 'a+')
    se = file("/dev/null", 'a+', 0)
    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())
    # 在子进程中执行代码
    funzioneDemo() # function demo
if name == 'main': 
    if platform.system() == "Linux":
        createDaemon()
    else:
        os._exit(0)
登录后复制

通过upstart方式实现

可以通过upstart把应用封装成系统服务,这里直接记录下完整示例。

1、编写python脚本

代码如下:

[root@local t27]
# cat test123.py
#!/usr/bin/env python
import os,time
while True :    
print time.time()    
time.sleep(1)
登录后复制


2、编写upstat配置文件

代码如下:

[root@local t27]
# cat /etc/init/mikeTest.confdescription "My test"author "Mike_Zhang@live.com"
start on runlevel [234]stop on runlevel [0156]
chdir /test/t27exec /test/t27/test123.pyrespawn
登录后复制

3、重新加载upstate

代码如下:

initctl reload-configuration
登录后复制

4、启动服务

代码如下:

[root@local t27]# start mikeTest
mikeTest start/running, process 6635
[root@local t27]# ps aux | grep test123.py
root      6635  0.0  0.0  22448  3716 ?        
Ss   09:55   0:00 python /test/t27/test123.py
root      6677  0.0  0.0 103212   752 pts/1   
 S+   09:56   0:00 grep test123.py
登录后复制


5、停止服务

代码如下:

[root@local t27]# stop mikeTest
mikeTest stop/waiting
[root@local t27]# ps aux | grep test123.py
root      6696  0.0  0.0 103212   752 pts/1    S+   09:56   0:00 grep test123.py
[root@local t27]#
登录后复制

通过bash脚本实现

1、python代码

代码如下:

[root@local test]# cat test123.py#!/usr/bin/env python
import os,time
while True :    print time.time()    time.sleep(1)
登录后复制


2、编写启动脚本

代码如下:

[root@local test]# cat start.sh#! /bin/sh
python test123.py &
登录后复制

3、启动进程

代码如下:

[root@local test]#./start.sh
登录后复制

如果直接用&启动进程:

代码如下:

python test123.py &
登录后复制

直接关闭ssh终端会导致进程退出。

通过screen、tmux等方式实现

如果临时跑程序的话,可以通过screen、tmux启动程序,这里描述下tmux启动的方式。

1、启动tmux

在终端输入tmux即可启动

2、在tmux中启动程序

直接执行如下命令即可(脚本参考上面的): python test123.py

3、直接关闭ssh终端(比如putty上的关闭按钮);

4、重新ssh上去之后,执行如下命令:

代码如下:

tmux attach
登录后复制

现在可以看到python程序还在正常执行。

windows下后台运行

在windows下没有深入的研究过,我经常用的方法是修改python脚本的扩展名为".pyw",双击即可后台运行,不需要修改任何代码。

 以上就是Python脚本后台运行的几种方式的内容,更多相关内容请关注PHP中文网(www.php.cn)!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号