简体   繁体   English

如何在 Linux 中将 python 脚本作为服务运行

[英]how to run python script as a service in Linux

I have a python script that I would like to be used as a service in Suse Linux.我有一个 python 脚本,我想在 Suse Linux 中将其用作服务。

I tried creating a script.conf file in /etc/init.d that looks like this:我尝试在 /etc/init.d 中创建一个 script.conf 文件,如下所示:

description "File service"
author  "Me"

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

chdir /app/file/bin
exec /app/file/bin/script.py
respawn

How do I test if this script is working ?如何测试此脚本是否有效? I have no idea what command to type to start running this service.我不知道输入什么命令来开始运行这个服务。 Any answers to this will be greatly appreciated thanks.对此的任何答案将不胜感激,谢谢。

Lets break answer in two parts first how to configure it and Second how to run and test it as process.让我们分两部分来回答,第一部分是如何配置它,第二部分是如何将它作为进程运行和测试。

How to configure?如何配置?

Configuration you have posted above is correct.您在上面发布的配置是正确的。 But file is supposed to be created under directory /etc/init/myscript-service.conf (That's what I follow in my scenario).但是文件应该在目录 /etc/init/myscript-service.conf 下创建(这就是我在我的场景中遵循的)。 Another configuration part is you have to make script file executable so that it can run as service.另一个配置部分是您必须使脚本文件可执行,以便它可以作为服务运行。

Linux command Linux 命令

chmod u+x /app/file/bin/script.py

You need to add below line in your python script.您需要在 python 脚本中添加以下行。

#!/usr/bin/python

And install upstart tool.并安装新贵工具。

After above all configuration you are ready to run script as service.完成以上所有配置后,您就可以将脚本作为服务运行了。

How to run and test?如何运行和测试?

Once you have created file myscript-service.conf you can start the service as normal service in linux using below command.创建文件 myscript-service.conf 后,您可以使用以下命令在 linux 中将服务作为普通服务启动。

service myscript-service start

It will give you process id.它会给你进程ID。 And you can start/stop/status it like normal service.您可以像正常服务一样启动/停止/状态它。

Logs you can find under您可以在下面找到日志

/var/log/upstart/myscript-service.log /var/log/upstart/myscript-service.log

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM