python程序怎么给别人运行_如何使Python脚本作为服务运行?
小編典典
我使用此代碼來守護(hù)我的應(yīng)用程序。它允許您start/stop/restart使用以下命令來編寫腳本。
python myscript.py start
python myscript.py stop
python myscript.py restart
除此之外,我還有一個(gè)init.d腳本來控制我的服務(wù)。這使您可以在操作系統(tǒng)啟動(dòng)時(shí)自動(dòng)啟動(dòng)服務(wù)。
這是一個(gè)簡(jiǎn)單的示例,可以助您一臂之力。只需將代碼移到一個(gè)類中,然后從run內(nèi)部的函數(shù)中調(diào)用它即可MyDeamon。
import sys
import time
from daemon import Daemon
class YourCode(object):
def run(self):
while True:
time.sleep(1)
class MyDaemon(Daemon):
def run(self):
# Or simply merge your code with MyDaemon.
your_code = YourCode()
your_code.run()
if __name__ == "__main__":
daemon = MyDaemon('/tmp/daemon-example.pid')
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.stop()
elif 'restart' == sys.argv[1]:
daemon.restart()
else:
print "Unknown command"
sys.exit(2)
sys.exit(0)
else:
print "usage: %s start|stop|restart" % sys.argv[0]
sys.exit(2)
暴發(fā)戶
如果您正在運(yùn)行使用Upstart的操作系統(tǒng)(例如CentOS
6)-您也可以使用Upstart來管理服務(wù)。如果您使用Upstart,則可以按原樣保留腳本,只需在下面添加如下內(nèi)容/etc/init/my-
service.conf
start on started sshd
stop on runlevel [!2345]
exec /usr/bin/python /opt/my_service.py
respawn
然后,您可以使用啟動(dòng)/停止/重新啟動(dòng)來管理服務(wù)。
例如
start my-service
stop my-service
restart my-service
這里提供了使用新貴的更詳細(xì)的示例。
2020-06-02
總結(jié)
以上是默认站点為你收集整理的python程序怎么给别人运行_如何使Python脚本作为服务运行?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 柳下惠梗怎么来的比喻什么人(柳下惠坐怀不
- 下一篇: 镜像VirtualBox 下安装 Cen