I created a python program, "test.py" and have saved it under /home/pi/. When I go to run it in the terminal using "python3 /home/pi/test.py" it runs properly and speaks "hello world". The code is shown below.
import os
import alsaaudio
m = alsaaudio.Mixer()
current_volume = m.getvolume()
m.setvolume(35)
os.system("espeak 'Hello World!'")
I want this program to start whenever my raspberry pi starts up. I tried to add this line in crontab but my raspberry pi doesn't execute the command. Does anyone know why my program won't execute?
#reboot python3 /home/pi/test.py
Here is an image of the syslog
can you try adding the full path to python3:
#reboot /usr/bin/python3 /home/pi/test.py
Also, regarding wanting to run the code on when the device boots - you can run your code as a service.
To do so create a .service file under /etc/systemd/system (for example my-code.service)
Enter the following inside the file
[Unit]
Description=My python service
After=network.target
[Service]
ExecStart=/usr/bin/python3 -u test.py
WorkingDirectory=/home/pi
[Install]
WantedBy=multi-user.target
Finally enable the service (in order for it to run on boot)
sudo systemctl enable my-code
If you want to run it independently you can also run
sudo systemctl start my-code
Related
writing a data logging program that is intended to run when raspberry boots. I'm using lxsessions autostart to launch a shell script that has the command to launch my python program (my python script requires sudo)
while I continue to debug I would like the terminal window to stay open if/when it encounters an error.
I had done this successfully once before but lost my work.
my autostart file is:
#!/bin/bash
#lxpanel --profile LXDE-pi
#pcmanfm --desktop --profile LXDE-pi
#lxterminal -e sudo sh /home/pi/launcher.sh
#xscreensaver -no-splash
my script file is:
#!/bin/sh
echo Script is running
sudo /usr/bin/python3 /home/pi/hms/hms5-1.py
I thought something like this (in the autstart file) would work, but no:
#lxterminal -e -hold sudo sh /home/pi/launcher.sh
a simple internet search spit out of examples on how to execute command at boot, even launching scripts but nothing has helped so far. Thank you in advance.....
So I rebuilt my Raspberry Pi and had to go through this again. So after I was able to get it to work once, I followed my instructions from before, edited them to be clearer the posted here. NOTE - I think the mistake I made before was using sudo (sudo nano) when I should have just used nano....
Also note the python program I am launching is /home/pi/hms/hms2-v2.py
*** setting this up is a 4 step process ***
YOU MUST HAVE XTERM
STEP 1 - INSTALL XTERM:
sudo apt-get install xterm
STEP 2
read https://www.raspberrypi.org/forums/viewtopic.php?t=227191
FIRST CREATE autostart here: /home/pi/.config/lxsession/LXDE-pi/autostart
NOTE THE FOLDERS BELOW /home/pi/.config/ MAY NOT EXIST, IF NOT CREATE THEM EXACTLY AS ABOVE. NOTE: the directory must be LXDE-pi NOT LXDE
Then edit the autostart file
by using nano ~/.config/lxsession/LXDE-pi/autostart
NOTE: DO NOT use sudo in the above command
put the following in the file:
#!/bin/bash
#lxpanel --profile LXDE-pi
#pcmanfm --desktop --profile LXDE-pi
sh /home/pi/launcher.sh
#xscreensaver -no-splash
Step 3
create the script (.sh) file: launcher.sh in the directory /home/pi
include the following in the file launcher.sh:
#!/bin/sh
echo starting script
xterm -T "HMS" -geometry 100x70+10+35 -hold -e sudo /usr/bin/python3 /home/pi/hms/hms2-v2.py
Step 4
make the .sh file executable with: sudo chmod +x launcher.sh
I have a shell script called kill.sh that helps me restart a python script I've written. I normally use pkill -f main.py to kill my forever-running python script. However, when I wrote it into a shell script it does not work.
My script
pkill -f main.py
ps aux | grep main.py # Still shows the process running.
While just executing pkill -f main.py in bash command line works as expected. Why is this?
This is not a satisfactory answer, as I cannot find out the root cause of why pkill -f does not work in a script. I ended up using a systemd Service file to manage my python process. Here's an example fyi.
[Unit]
Description=Service Name
[Service]
Environment=PYTHONUNBUFFERED=1
ExecStart=/path/to/python /path/to/python/script.py
Restart=on-failure
RestartSec=5s
WorkingDirectory=/python/project/dir/
Name the file main.service and place it in /lib/systemd/system/
Running the service systemctl start main.service
Stop the service systemctl stop main.service
Restart the service systemctl restart main.service
Show status and output systemctl status main.service -l
Now I don't have to worry about multiple processes running. If the program dies it'll even restart.
I've successfully manage to run my GUI python application as a service in a Raspberry pi. The used unit file:
[Unit]
Description=Example systemd service.
After=graphical.target
[Service]
Type=simple
Environment="Display=:0"
Environment=XAUTHORITY=/home/pi/.Xauthority
WorkingDirectory=/home/pi/tf/
ExecStart=/home/pi/tf/myApp.py
Restart=always
RestartSec=10s
KillMode=process
Timeout=infinity
[Install]
WantedBy=graphical.target
At the beginning of my python application i added the route python3 like this:
#! /address/where/is/python3
The problem is that i can't do the same in Ubuntu.
I think is because .Xauthority file does not exist.
In ubuntu i ran
echo $XAUTHORITY
and i got:
/run/user/1000/Xauthority
then i change these lines:
Environment=XAUTHORITY=/run/user/1000/Xauthority
WorkingDirectory=/home/sergio/tf/
ExecStart=/home/sergio/tf/myApp.py
with "journalctl -u myApp -f" displays the following error:
cannot connect to X server
Any idea what can it be?
I solve this problem by following the steps by htorque in this post https://askubuntu.com/questions/21923/how-do-i-create-the-xauthority-file
Follow this steps:
1-Open System > Preferences > Startup Applications
2-Click on Add :
3-Name: Xauthority
4-Command: /bin/bash -c 'ln -s -f "$XAUTHORITY"
~/.Xauthority' Comment: Creates a symbolic link from ~/.Xauthority to
$XAUTHORITY and add the entry by clicking on Add.
Now every time you log in, it should create the link to the current
authority file.
So now we have the file .Xauthority in ~/
Finally service file myApp.service was updated like this:
Environment="Display=:0"
Environment=XAUTHORITY=/home/"yourUsername"/.Xauthority
I have a Django project and I am using pykafka. I have created two files named producer.py and consumer.py inside the project. I have to change directory into the folder where these are present and then separately run python producer.py and consumer.py from the terminal. Everything works great.
I deployed my project online and the web-app is running so I want to run the producer and consumer automatically in the background. How do i do that?
EDIT 1: On my production server I did nohup python name_of_python_script.py & to execute it in the background. This works for the time being but is it a good solution?
You can create a systemd service MyKafkaConsumer.service under /etc/systemd/system with the following content:
[Unit]
Description=A Kafka Consumer written in Python
After=network.target # include any other pre-requisites
[Service]
Type=simple
User=your_user
Group=your_user_group
WorkingDirectory=/path/to/your/consumer
ExecStart=python consumer.py
TimeoutStopSec=180
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
In order to start the service (and configure it in order to run on boot) you should run
systemctl enable MyKafkaConsumer.service
systemctl start MyKafkaConsumer.service
To check its status:
systemctl status MyKafkaConsumer
And to see the logs:
journactl -u MyKafkaConsumer -f
(or if you want to see the last 100 lines)
journalctl -u MyKafkaConsumer -n 100
You'd need to create a similar service for your producer too.
There are a lot of options for systemd services. You can refer to this article if you need any further clarifications. It shouldn't be hard to find guides and additional material online though.
I am currently running ngrock and a python app concurrently on a specific port to text my raspberry pi, and have it respond accordingly to my message via Twilio. Each time my raspberry pi boots up, or reboots, I need to manually start the services again with ./ngrok http 5000 and python /path/to/file/app.py. To avoid that, I edited my cron jobs as follows, and wrote a script called startService.py. However, it doesn't seem to be functioning properly, as I do not receive answers to texts after reboot. Any ideas?
Cron:
# m h dom mon dow command
*/5 * * * * python /rasp/system/systemCheck.py
#reboot python /Rasp/system/twilio/startService.py &
startService.py
import os
os.system('/./ngrok http -subdomain=ABC123 5000')
os.system('python /Rasp/system/twilio/starter/app.py')
You did not mention your OS, assuming your OS using Upstart for boot you can create upstart script to start then your process will automatically spawn at boot or when the process die. For ngrok, create a file /etc/init/ngrok.conf
# Ngrok
#
# Create tunnel provided by ngrok.io
description "Ngrok Tunnel"
start on runlevel [2345]
stop on runlevel [!2345]
respawn
respawn limit 10 5
umask 022
exec /ngrok http -subdomain={{My Reserved Subdomain}} 5000
Now it will automaticlaly start at boot. If you want to start manually just issue command.
$ sudo service ngrok start
Just for suggestion, putting your binary on root directory / is not good practice.
Reference:
http://notes.rioastamal.net/2016/05/starting-ngrok-automatically-at-boot.html
After multiple failed attempts I have seem to come up with a working system. I first had to authorize the root user to use my ngrok account by doing the following:
sudo su
./ngrok authtoken {{Insert Your Auth Token Here}}
exit
Then, I created ngrokLauncher.sh and appLauncher.sh as shown.
ngrokLauncher.sh:
#!/bin/sh
# launcher.sh
cd /
./ngrok http -subdomain={{My Reserved Subdomain}} 5000 &
cd /
appLauncher.sh:
#!/bin/sh
# launcher.sh
cd /Storage/system/twilio/starter
python app.py &
cd /
Then, I modified the file permissions so they would be able to be run on startup sudo chmod 755 ngrokLauncher.sh && sudo chmod 755 appLauncher.sh. Lastly, I edited the Cron Jobs as follows:
Crontab:
# m h dom mon dow command
*/5 * * * * python /SKYNET/system/systemCheck.py
#reboot sh /Storage/ngrokLauncher.sh >/Storage/logs/cronlog 2>&1
#reboot sh /Storage/appLauncher.sh >/Storage/logs/cronlog 2>&1
Then after running sudo reboot, the system restarted and I received a response to my sms from the python app.