在centos 7.6中使用python3.7写一个带daemon.notify的systemd service

python-systemd-tutorial有一个demo, 但是这个demo在centos 76 + python37下,无法运行,一直报错:

raise TypeError("state must be an instance of Notification")       

但是这个代码 ,在我的Fedora36上, 可以直接运行, 如下:

创建/etc/systemd/system/demo.service, 注: 去除注释

# /etc/systemd/system/demo.service

[Unit]
Description=Python Demo Service


[Service]
ExecStart=/usr/bin/python3 /develop/systemd/demo.py
Environment=PYTHONUNBUFFERED=1
Restart=on-failure
Type=notify

# 我改成了直接使用root用户
User=root


[Install]
WantedBy=default.target

创建python文件: /develop/systemd/demo.py

  1 # Python script for the Python Demo Service
  2
  3 if __name__ == '__main__':
  4     import time
  5     import systemd.daemon
  6
  7     print('Starting up ...')
  8     time.sleep(10)
  9     print('Startup complete')
 10     # Tell systemd that our service is ready
 11     systemd.daemon.notify('READY=1')
 12
 13     while True:
 14         print('Hello from the Python Demo Service')
 15         time.sleep(5)

从错误的信息肯, 跟python包systemd有关,  fedora 36 已经默认安装了 rpm包:

python3-systemd-234-20.fc36.x86_64

而centos 76上没有这个包,也找不到想应的rpm包, 使用pip3尝试安装:

ip3 install systemd

这个包来自: systemd · PyPI, 这个页面有例子, 与上面的demo.py中第5行和11行, 使用的:

    5      import systemd.daemon

    11  systemd.daemon.notify('READY=1')

有区别, 于是最终在centos76上的demo.py改成:

  1 # Python script for the Python Demo Service
  2
  3 if __name__ == '__main__':
  4     import time
  5     from systemd.daemon import notify, Notification
  6     
  7     print('Starting up ...')
  8     time.sleep(10)
  9     print('Startup complete')
 10     # Tell systemd that our service is ready
 11     notify(Notification.READY)
 12     
 13     while True:
 14         print('Hello from the Python Demo Service')

 15         time.sleep(5) 

 改完之后, systemctl start demo 就OK了. 在/var/log/messages中有了正确的消息:

Mar 22 16:29:17 cq-packs-92 python3: Startup complete
Mar 22 16:29:17 cq-packs-92 systemd: Started Python Demo Service.
Mar 22 16:29:17 cq-packs-92 python3: Hello from the Python Demo Service

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值