Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting a Python script using rc-service

Tags:

python

rc

I am trying to make rc-service start a Python script on startup (Alpine Linux). I have made a simplified example just to get things to work, but no luck.

I have added local to the default run-level, and I have two files in /etc/local.d/ - both owned by root:

one_api.start:

#!/sbin/openrc-run
command=one_api.py

one_api.py:

#!/usr/bin/python3

import uvicorn
from fastapi import FastAPI


app = FastAPI()


@app.get('/')
async def get_root():
    return {'message':'hello, world!'}


if __name__ == '__main__':
    uvicorn.run('one_api:app', host='127.0.0.1', port=8000, log_level='info')

When I try to start local I get * Starting local ... [!!]. I looked for a log in /var/log/ but rc-service doesn't write a log to that location, and I can't find it anywhere else. If I run the Python script manually it works fine.

Trying to start the service by itself also doesn't work:

$ sudo ./one_api.start start
 * Starting one_api.start ...
Segmentation fault
 * Failed to start one_api.start       [ !! ]
 * ERROR: one_api.start failed to start
like image 378
henrikstroem Avatar asked Sep 11 '26 03:09

henrikstroem


1 Answers

Create a bash script (call it my_bash_script.sh) with:

#!/bin/bash
cd <path to python script>
python <python script>

and put it (as root) some place like /usr/local/bin. Make sure the executable bit is set:

chmod ugo+x /usr/local/bin/my_bash_script.sh

Create a minimal service file (call it my_service):

#!/sbin/openrc-run
command="/usr/local/bin/my_bash_script.sh"
pidfile="/run/${RC_SVCNAME}.pid"
command_args="-p ${pidfile}"
command_background=True

Put the service file (as root) in /etc/init.d; set permissions:

chmod ugo+x /etc/init.d/my_service

Now you should be able to start/restart/stop it normally:

rc-service my_service start
rc-service my_service restart
rc-service my_service stop
like image 164
erg Avatar answered Sep 12 '26 17:09

erg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!