Python開發【筆記】:python程式添加到systemctl系統服務,pythonsystemctl

來源:互聯網
上載者:User

Python開發【筆記】:python程式添加到systemctl系統服務,pythonsystemctl
systemctl系統服務

  環境:centos7

  systemctl服務使用詳解

 

實現

正常情況下我們在/usr/lib/systemd/system/目錄下,建立一個以.service 尾碼的檔案,如cdr.service

[Unit]Description=cdrAfter=network.target[Service]ExecStart=/opt/pbx/cdr/cdr.pyType=forking[Install]WantedBy=multi-user.target

使用方式:

# 啟動systemctl start cdr# 關閉systemctl stop cdr#查看狀態systemctl status cdr#開啟自啟動systemctl enable cdr#關閉開啟自啟動systemctl enable cdr

正常的python程式都可以這麼用,但是下面這種情況下,還使用上面的.servcie檔案建立方式就不好使了,如下

#!/usr/bin/env python# -*- coding:utf-8 -*-import loggingimport timeimport syslogging.basicConfig(level=logging.INFO)def daemon():    import os    # create - fork 1    try:        pid = os.fork()        if pid > 0:            return pid    except OSError as error:        logging.error('fork #1 failed: %d (%s)' % (error.errno, error.strerror))        return -1    # it separates the son from the father    os.chdir('/opt/pbx')    os.setsid()    os.umask(0)    # create - fork 2    try:        pid = os.fork()        if pid > 0:            return pid    except OSError as error:        logging.error('fork #2 failed: %d (%s)' % (error.errno, error.strerror))        return -1    sys.stdout.flush()    sys.stderr.flush()    si = open("/dev/null", 'r')    so = open("/dev/null", 'a+')    se = open("/dev/null", 'a+')    os.dup2(si.fileno(), sys.stdin.fileno())    os.dup2(so.fileno(), sys.stdout.fileno())    os.dup2(se.fileno(), sys.stderr.fileno())    return 0def main():    pid = daemon()    if pid:        return pid    while True:        logging.info('----------')        time.sleep(1)main()

這次最大的區別就是在python程式中fork了一個子進程,這種情況下第一種方式就不好使了,經過多次測試發現下面這種方式可以實現我們的效果

[Unit]Description=lzlAfter=network.target[Service]Type=oneshotRemainAfterExit=yesExecStart=/usr/bin/python3 /home/lzl/workspace/cdrservice/main.py[Install]WantedBy=multi-user.target

  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.