Python指令碼後台啟動並執行幾種方式

來源:互聯網
上載者:User

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)
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 "Mike_Zhang@live.com"

 

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",雙擊即可後台運行,不需要修改任何代碼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.