歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python腳本後台運行

Python腳本後台運行

日期:2017/3/1 9:26:28   编辑:Linux編程

問題描述:

環境: CentOS6.4

一個用Python寫的監控腳本test1.py,用while True方式一直運行,在ssh遠程(使用putty終端)時通過以下命令啟動腳本:

python test1.py &

現在腳本正常運行,通過ps能看到進程號,此時直接關閉ssh終端(不是用exit命令,是直接通過putty的關閉按鈕執行的), 再次登錄後發現進程已經退出了。

通過後台啟動的方式該問題已經解決,這裡總結下,也方便我以後查閱。

Linux 下後台運行

通過fork實現

Linux環境下,在c中守護進程是通過fork方式實現的,python也可以通過該方式實現,示例代碼如下:

#!/usr/bin/env python
#E-Mail : [email protected]
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.conf
description "My test"
author "[email protected]"

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

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

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的文章您也可能喜歡,不妨看看:

Python:在指定目錄下查找滿足條件的文件 http://www.linuxidc.com/Linux/2015-08/121283.htm

Python2.7.7源碼分析 http://www.linuxidc.com/Linux/2015-08/121168.htm

無需操作系統直接運行 Python 代碼 http://www.linuxidc.com/Linux/2015-05/117357.htm

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved