SystemD Setup Can't Find Python? - 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.

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.

Python not found using Systemctl

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).

Start a python script at startup automatically?

I followed multiple tutorials available on stackoverflow about starting a python script at startup but none of them works.
I need to activate a virtualenv then start a flask server
I tried
init.d method
I made an start.sh in /etc/init.d/
#!/bin/sh
### BEGIN INIT INFO
# Provides: skeleton
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Should-Start: $portmap
# Should-Stop: $portmap
# X-Start-Before: nis
# X-Stop-After: nis
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# X-Interactive: true
# Short-Description: Example initscript
# Description: This file should be used to construct scripts to be
# placed in /etc/init.d.
### END INIT INFO
cd /home/ion/
source /home/ion/py35/bin/activate
cd /home/ion/Desktop/flask/
nohup python main.py &
echo "Done"
Its permissions are chmod at +x
ion#aurora:/etc/init.d$ ll start.sh
-rwxr-xr-x 1 root root 625 Jun 25 19:10 start.sh*
Went to /etc/rc.local
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
/etc/init.d/start.sh
exit 0
Didn't work
cronjob method
sudo crontab -e
and appended
#reboot sh '/etc/init.d/start.sh'
Didn't worked either , where am I wrong?
Manual triggered logs
(py35) ion#aurora:~/Desktop/flask$ python main.py
WARNING:tensorflow:From /home/ion/Desktop/flask/encoder.py:57: calling l2_normalize (from tensorflow.python.ops.nn_impl) with dim is deprecated and will be removed in a future version.
Instructions for updating:
dim is deprecated, use axis instead
2018-06-25 19:34:05.511943: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
* Serving Flask app "main" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://localhost:5505/ (Press CTRL+C to quit)
* Restarting with stat
1) Don't use old "init.d" method. Use something modern. If you have Ubuntu 15.04 and higher, you can use Systemd to create daemon that will be started automatically at startup. If you have for example Ubuntu older than 15.04 - use Upstart.
For Systemd:
Create unit file in /lib/systemd/system/you_service_name.service with the following content (as far as I can see your python script doesn't spawn new process while running, so Type should be simple. More info here):
[Unit]
Description=<your_service_name>
After=network.target network-online.target
[Service]
Type=simple
User=<required_user_name>
Group=<required_group_name>
Restart=always
ExecStartPre=/bin/mkdir -p /var/run/<your_service_name>
PIDFile=/var/run/<your_service_name>/service.pid
ExecStart=/path/to/python_executable /path/to/your/script.py
[Install]
WantedBy=multi-user.target
Save this file and reload systemd:
sudo systemctl daemon-reload
Then add your service to autostart:
sudo systemctl enable you_service_name.service
you should see that Systemd created required symlinks after enable action.
Reboot and see if it's up and running (ps aux | grep python or sudo systemctl status you_service_name.service). If there is something weird - check Systemd journal:
sudo journalctl -xe
UPD:
To launch your python script in desired virtualenv, just use this expression in your service unit file:
ExecStart=/venv_home/path/to/python /venv_home/path/to/your/script.py
2) You can also use crontab, but you need to specify full path for desired shell there, for example:
#reboot /bin/bash /path/to/script.sh
If you need additional help - just let me know here.

How can I put my python code in startup in raspberry pi

I wanted to put my python code in boot in raspberry pi.
I tried rc.local, ./bashrc but while booting program is working & I am using opencv + camera +voice command. That's not working in boot.
Please give me a way to run voice + camera + opencv + python code in boot.
I would suggest to make it run as a service as mentioned in method 4 of following article:
https://www.dexterindustries.com/howto/run-a-program-on-your-raspberry-pi-at-startup/
Step 1– Create A Unit File
Open a sample unit file using the command as shown below:
sudo nano /lib/systemd/system/sample.service
Add in the following text :
[Unit]
Description=My Sample Service
After=multi-user.target
[Service]
Type=idle
ExecStart=/usr/bin/python /home/pi/sample.py
[Install]
WantedBy=multi-user.target
You should save and exit the nano editor.
This defines a new service called “Sample Service” and we are requesting that it is launched once the multi-user environment is available. The “ExecStart” parameter is used to specify the command we want to run. The “Type” is set to “idle” to ensure that the ExecStart command is run only when everything else has loaded. Note that the paths are absolute and define the complete location of Python as well as the location of our Python script.
In order to store the script’s text output in a log file you can change the ExecStart line to:
ExecStart=/usr/bin/python /home/pi/sample.py > /home/pi/sample.log 2>&1
The permission on the unit file needs to be set to 644 :
sudo chmod 644 /lib/systemd/system/sample.service
Step 2 – Configure systemd
Now the unit file has been defined we can tell systemd to start it during the boot sequence :
sudo systemctl daemon-reload
sudo systemctl enable sample.service
Reboot the Pi and your custom service should run:
sudo reboot

Run Python script on start-up (Arch Linux ARM on Raspberry Pi)

I have a Python script on my Raspberry Pi running on Arch Linux ARM. To start the script, I use this command:
sudo python2 screen/screen.py
and it works perfectly. Now, my question is, how I can run this script automatically on start-up?
In the folder /etc/systemd/system/ make a file named screen.service
The contents of that file might look like this (change for your use):
[Unit]
Description=Launches screen with my config
After=network.target
[Service]
Type=simple
ExecStart=command_you_want_to_run
RemainAfterExit=true
[Install]
WantedBy=multi-user.target
When you're finished run systemctl enable screen.service
The WantedBy line tells systemd where to make the symlink.
To learn more about the options for service unit files check out the docs: man systemd.service

Categories

Resources