DIV CSS 佈局教程網

Python 腳本在後台運行的幾種方式
編輯:JavaScript基礎知識     

有一個用 Python 撰寫、以 while True 持續運行的監控腳本 test1.py。在透過 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)
    # 第二次 fork 進程
    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()

if __name__ == '__main__':
    if platform.system() == "Linux":
        createDaemon()
    else:
        os._exit(0)

方式二:透過 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、編寫 upstart 配置文件:

[root@local t27]# cat /etc/init/mikeTest.conf
description "My test"
author "Mike_Zhang@live.com"

start on runlevel [234]
stop on runlevel [0156]

chdir /test/t27
exec /test/t27/test123.py
respawn

3、重新載入 upstart:

initctl reload-configuration

4、啟動服務:

[root@local t27]# start mikeTest
mikeTest start/running, process 6635

5、停止服務:

[root@local t27]# stop mikeTest
mikeTest stop/waiting

方式三:透過 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、啟動進程:執行 ./start.sh 即可。若直接用 python test123.py & 啟動,直接關閉 SSH 終端仍會導致進程退出。

方式四:透過 screen、tmux 等方式實現

若是臨時跑程序,可用 screen 或 tmux。以 tmux 為例:在終端輸入 tmux 即可啟動;接著在 tmux 中執行 python test123.py;然後直接關閉 SSH 終端;重新登入後執行 tmux attach,就能看到 Python 程序仍在正常執行。

Windows 下後台運行

在 Windows 下我沒有深入研究,常用的方法是把 Python 腳本的副檔名改為 ".pyw",雙擊即可在後台運行,無需改動任何程式碼。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved