Python not found using Systemctl - python

Hy guys, I have an error in systemctl that tells me that the python was not found. In my .service file below, I run celery-beat. In my tasks.py, I have a code snippet that uses os.system to run python code.
# My .service
[Unit]
Description=Celery Service
After=network.target
[Service]
Type=forking
User=ubuntu
Group=ubuntu
WorkingDirectory=/home/ubuntu/my_project_folder
ExecStart=/bin/sh -c '/home/ubuntu/enviq/bin/celery -A projectdjango worker -l info -B --scheduler django_celery_beat.schedulers:DatabaseScheduler &'
ExecStop=/bin/kill -s TERM $MAINPID
[Install]
WantedBy=multi-user.target
# Error when execute sudo journalctl -xe
Apr 30 16:13:01 ip-172-31-17-187 sh[16228]: [2020-04-30 13:13:01,155: INFO/MainProcess] Received task: app_iq_option01.tasks.get_candles_tasks[d1d14df
Apr 30 16:13:01 ip-172-31-17-187 sh[16228]: sh: 1: python: not found
Apr 30 16:13:01 ip-172-31-17-187 sh[16228]: sh: 1: python: not found
# In this line I use the module os to call main_tasks.py
command = "python main_tasks.py {} {} {} '%s'".format(cred.email, cred.password, cred.max_samples)
command = command % coins
os.system(command)
When I run the command to run the celery through the terminal without using systemctl, it works normal. Anyone can help me with this? I really appreciate! It seems that systemd does not recognize my virtualenv (It calls venviq).

Related

Autostart and automatically restart Python Script Raspberry Pi

I know how to autostart a python script (or so I thought). But I want a programm or something, if my python script is not running anymore, it should start the script again. Has anyone a idea how to do this?
Edit:
I tried running it as a service but that didnt work.
import bluetooth
import pygame
pygame.mixer.init()
server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
port = 22
server_sock.bind(("",port))
server_sock.listen(1)
client_sock,address = server_sock.accept()
print ("Verbindung Hergestellt mit: ", address)
while True:
recvdata = client_sock.recv(1024)
print ("Nachricht bekommen: %s" % recvdata)
pygame.mixer.pause()
if (recvdata == b"h"):
sound = pygame.mixer.Sound('/home/maxi/Desktop/test.wav')
playing = sound.play()
if (recvdata == b"p"):
sound = pygame.mixer.Sound('/home/maxi/Desktop/test2.wav')
playing = sound.play()
if (recvdata == b"k"):
break
client_sock.close()
server_sock.close()
My startscript is:
[Unit]
Description=MaxiTest
After=multi-user.target
[Service]
Type=simple
Restart=always
ExecStart=/usr/bin/python3 /home/maxi/Desktop/btsound1.py
[Install]
WantedBy=multi-user.target
You can search more about how a python script can perform as a service or daemon. There are many solutions in this link:
How to make a Python script run like a service or daemon in Linux
Between all solutions, I prefer 3 of them (I'm not very familiar with raspberry-pi, so check compatibility):
Cronjob: You can create a cronjob for the script and the OS will run it every x seconds/minutes/... automatically and periodically.
Systemctl/Systemd: Create a custom service file for your script and start and enable it in Systemd. A complete guide is here:
https://medium.com/codex/setup-a-python-script-as-a-service-through-systemctl-systemd-f0cc55a42267
You chose systemd (after editing);
In /PATH_project/ create 2 bash scripts like this:
#!/bin/bash
# This is start.sh
cd /home/maxi/Desktop/
/usr/bin/python3 btsound1.py
And create stop.sh:
#!/bin/bash
for KILLPID in `ps ax | grep ‘myservice’ | awk ‘{print $1;}’`; do
kill -9 $KILLPID;
done
Then give execution permission to both files using:
chmod a+x start.sh
chmod a+x stop.sh
Then create a myservice.service file in /etc/systemd/system :
[Unit]
Description=myservice service
Wants=network-online.target
After=network.target network-online.target
[Service]
Type=simple
Restart=always
ExecStart=/bin/bash /home/maxi/Desktop/start.sh
ExecStop=/bin/bash /home/maxi/Desktop/stop.sh
RestartSec=5
TimeoutSec=60
RuntimeMaxSec=infinity
PIDFile=/tmp/mydaemon.pid
[Install]
WantedBy=multi-user.target
Then:
sudo systemctl daemon-reload
sudo systemctl start myservice.service
sudo systemctl status myservice.service
Benefits of using such bash scripts is that you can handle some more things in this way. For example if you are using a virtual environment, you can use source activate in start.sh file before running the script.py .
Supervisord: Install Supervisor and create a supervisord.conf file for your script. A good guide is here:
https://csjourney.com/managing-processes-with-supervisor-in-depth-tutorial/
I found what was the problem. I used rc.local and started the program 10 seconds after boot. The system needed time first to set up before I could start the script.

Can't get script to run from systemd or cron

I have a setup where I have a servercabinet with an external display that shows various system information. I only want it to turn on when I am present though, and I have made it soundactivated using SoundMeter https://github.com/shichao-an/soundmeter and a cheap USB microphone. When run manually everything works as it sohuld, but when i try to run it as a systemd service or a cronjob, it wont execute the second script that starts the display. From the logs I can see that Soundmeter works as it should, but it doesn't fire up the display.
Systemd service:
[Unit]
Description=Soundmeter
[Service]
Type=simple
Restart=always
#RestartSec=120
User=pi
ExecStart=/usr/local/bin/soundmeter -t +25 -a exec -e /opt/sysdroidUHHD/trigger.sh
[Install]
WantedBy=multi-user.target
Cronjob
#reboot /usr/local/bin/soundmeter -t +25 -a exec -e /opt/sysdroidUHHD/trigger.sh &
Contents of trigger.sh
#!/bin/bash
python3 /opt/sysdroidUHHD/sysdroid_main.py
exit 0
Any and all help is appreciated.
Remove that exit 0 from trigger.sh. Make sure your sysdroid_main.py starts some server or daemon that won't exit.

How do I run a bash-script from a system service?

So I'm trying to launch a tmux screen from a bash script which will then host a (python) discordbot. That bash script should in turn be launched from a system service so that the discordbot always launches with the physical server itself.
It seems that it gets stuck somewhere for some reason... I've been looking for ages for a solution but haven't been able to find one.
Here is the system service output:
● ubuntubot.service - UbuntuBot
Loaded: loaded (/etc/systemd/system/ubuntubot.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2021-08-13 18:39:26 CEST; 1min 58s ago
Main PID: 27366 (tmux: server)
Tasks: 2 (limit: 19060)
Memory: 4.9M
CGroup: /system.slice/ubuntubot.service
├─27366 /usr/bin/tmux new-session -d -s ubuntubot
└─27367 -bash
Here is my service file:
[Unit]
Description=UbuntuBot
After=network.target
[Install]
WantedBy=multi-user.target
[Service]
Type=simple
ExecStart=/usr/bin/bash /home/flynn/Minecraft/CreativeServer/DiscordBot/launchbot.sh start
Restart=always
RestartSec=5
And this is my bash script:
#!/bin/bash
#This script launches the Ubuntubot in a different tmux screen
#Start tmux ubuntu-session:
/usr/bin/tmux new-session -d -s ubuntubot
#Start UbuntuBot
/usr/bin/tmux send-keys -t ubuntubot "python3 ~/Minecraft/CreativeServer/DiscordBot/Ubuntubot.py" Enter
Maybe this is a horrible way to do it i have honestly no idea... I just need some help cause this is taking me wayyy to long on my own:)

SystemD Setup Can't Find Python?

I have a cronjob running on AWS EC2, that I usually launch via crontab:
0 */6 * * * sudo python3 /opt/homeDirectoryForMyApp/manage.py myCronJob --settings=server.settings.production
This works correctly as expected. Now I'm trying to launch the same job via SystemD.
myCronJob.service:
[Unit]
Description=myCronJob Service
Wants=myCronJob.timer
[Service]
ExecStart='/usr/bin/python3.7' manage.py myCronJob --settings=server.settings.production
WorkingDirectory=/opt/homeDirectoryForMyApps/
[Install]
WantedBy=multi-user.target
myCronJob.timer:
[Unit]
Description=launch myCronJob
Requires=myCronJob.service
[Timer]
Unit=myCronJob.service
OnCalendar=00/2:10
[Install]
WantedBy=rss.target
I'm getting this in journalctl (via journalctl -u myCronJob):
Jan 02 22:45:03 ip-###-##-#-### systemd[3760]: myCronJob.service: Failed at step CHDIR spawning /usr/bin/python3.7: No such file or directory
But /usr/bin/python3.7 does exist at that path:
ubuntu#ip-###-##-#-###:/etc/systemd/system$ cd /usr/bin
ubuntu#ip-###-##-#-###:/usr/bin$ ls python3.7
python3.7
What am I missing?
The error you are seeing is:
Failed at step CHDIR spawning /usr/bin/python3.7: No such file or directory
This suggests that the problem actually lies with your WorkingDirectory setting in your unit file (step CHDIR means "the error occurred when trying to change directory").
There is probably a typo in your WorkingDirectory path in your unit file.

Run multiple commands while starting docker services

I am trying to run two different commands when doing docker-compose up.
My command: parameter looks like:
gunicorn --reload analytics_api:api --workers=3 --timeout 10000 -b :8083 && exec python /analytics/model_download.py
But when I run this the container fails with the error:
gunicorn: error: unrecognized arguments: && exec python
/analytics/model_download.py
The second part of the command python /analytics/model_download.py, is used to download some dependencies from a sharedpath to a directory inside the container.
I want to run it while the service is up, not during the build.
What is going wrong here?
One way can be to have a startup shell script as the command which has both these entries
startup.sh
#start this in background if the other process need not wait for completion
exec python /analytics/model_download.py &
gunicorn --reload analytics_api:api --workers=3 --timeout 10000 -b :8083
while true
do
sleep 5
done
Adding bash -c before the command solved the problem.
The command value will look like:
bash -c "python model_download.py && gunicorn --reload analytics_api:api -- workers=3 --timeout 10000 -b :8083"

Categories

Resources