Upstart python script - python

I need to run code located /home/pi/Hello_on_startup.py each time RaspberryPi restarts
For that I created hello.conf file in /etc/init/ directory
description "A script controlled by upstart"
author "Anton"
start on runlevel [2345]
stop on runlevel [016]
respawn
exec /home/pi/Hello_on_startup.py`
When I run command sudo start hello I get an answer Unknown job: hello

You need a script...end script block in your conf file for it to be recognised, as shown here. Your resulting hello.conf file would look as follows:
description "A script controlled by upstart"
author "Anton"
start on runlevel [2345]
stop on runlevel [016]
respawn
script
exec /home/pi/Hello_on_startup.py`
end script
There is also a similar question on AskUbuntu.

Related

Crontab not starting python program

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

How to have a Python Script run 24/7

I have a python script called post.py that checks for HTTP "POST" methods to my server. This is all being held on an AWS EC2 instance. I want it so that the service is constantly running this python script and that I don't have to open a command line prompt and run: python post.py
How do you set up a python script like this?
You should be using supervisord to daemonize your script. Your config file should look something like this:
[program:post]
command: /usr/bin/python -m post
directory: /home/ubuntu/post # if post.py is in a folder called post that lives in home/ubuntu
autostart: true
I found out how to daemonize my script very easily:
I went to /etc/init/ and added a file called post.config.
I put in this:
start on runlevel [2345]
stop on runlevel [!2345]
env AN_ENVIRONMENTAL_VARIABLE=i-want-to-set
respawn
exec /home/ubuntu/Files/mysite/post.py
And now it is working perfectly!
If you meant to detach the execution from terminal you can use nohup(http://www.cyberciti.biz/tips/nohup-execute-commands-after-you-exit-from-a-shell-prompt.html) for that,else if you wanted to execute the post.py more than once in a scheduled fashion. you can use cron job for this - linux utilty.If you want to do this in python you can check this out https://docs.python.org/2/library/sched.html

managing uWSGI with Upstart

I am trying to configure uWSGI with Upstart.
I created the file /etc/init/uwsgi-flask.conf:
description "uwsgi for flask"
start on runlevel [2345]
stop on runlevel [06]
exec /appdir/virtualenvdir/bin/uwsgi /appdir/virtualenvdir/uwsgi.ini --die-on-term
On reboot, it starts up correctly, but I am not able to stop the service.
If I type on shell initctl stop uwsgi-flask, it gives:
initctl: Unknown instance:
anyone has any idea?
You probably have daemonize=some/log/file/path in your ini file. That will make the process exit with a "normal" exit code, so Upstart will figure that you wanted the job stopped and terminate the job.
Remove daemonize and upstart will track the process in the foreground.

Python script as linux service/daemon

Hallo,
I'm trying to let a python script run as service (daemon) on (ubuntu) linux.
On the web there exist several solutions like:
http://pypi.python.org/pypi/python-daemon/
A well-behaved Unix daemon process is tricky to get right, but the required steps are much the same for every daemon program. A DaemonContext instance holds the behaviour and configured process environment for the program; use the instance as a context manager to enter a daemon state.
http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
However as I want to integrate my python script specifically with ubuntu linux my solution is a combination with an init.d script
#!/bin/bash
WORK_DIR="/var/lib/foo"
DAEMON="/usr/bin/python"
ARGS="/opt/foo/linux_service.py"
PIDFILE="/var/run/foo.pid"
USER="foo"
case "$1" in
start)
echo "Starting server"
mkdir -p "$WORK_DIR"
/sbin/start-stop-daemon --start --pidfile $PIDFILE \
--user $USER --group $USER \
-b --make-pidfile \
--chuid $USER \
--exec $DAEMON $ARGS
;;
stop)
echo "Stopping server"
/sbin/start-stop-daemon --stop --pidfile $PIDFILE --verbose
;;
*)
echo "Usage: /etc/init.d/$USER {start|stop}"
exit 1
;;
esac
exit 0
and in python:
import signal
import time
import multiprocessing
stop_event = multiprocessing.Event()
def stop(signum, frame):
stop_event.set()
signal.signal(signal.SIGTERM, stop)
if __name__ == '__main__':
while not stop_event.is_set():
time.sleep(3)
My question now is if this approach is correct. Do I have to handle any additional signals? Will it be a "well-behaved Unix daemon process"?
Assuming your daemon has some way of continually running (some event loop, twisted, whatever), you can try to use upstart.
Here's an example upstart config for a hypothetical Python service:
description "My service"
author "Some Dude <blah#foo.com>"
start on runlevel [234]
stop on runlevel [0156]
chdir /some/dir
exec /some/dir/script.py
respawn
If you save this as script.conf to /etc/init you simple do a one-time
$ sudo initctl reload-configuration
$ sudo start script
You can stop it with stop script. What the above upstart conf says is to start this service on reboots and also restart it if it dies.
As for signal handling - your process should naturally respond to SIGTERM. By default this should be handled unless you've specifically installed your own signal handler.
Rloton's answer is good. Here is a light refinement, just because I spent a ton of time debugging. And I need to do a new answer so I can format properly.
A couple other points that took me forever to debug:
When it fails, first check /var/log/upstart/.log
If your script implements a daemon with python-daemon, you do NOT use the 'expect daemon' stanza. Having no 'expect' works. I don't know why. (If anyone knows why - please post!)
Also, keep checking "initctl status script" to make sure you are up (start/running). (and do a reload when you update your conf file)
Here is my version:
description "My service"
author "Some Dude <blah#foo.com>"
env PYTHON_HOME=/<pathtovirtualenv>
env PATH=$PYTHON_HOME:$PATH
start on runlevel [2345]
stop on runlevel [016]
chdir <directory>
# NO expect stanza if your script uses python-daemon
exec $PYTHON_HOME/bin/python script.py
# Only turn on respawn after you've debugged getting it to start and stop properly
respawn

Need help running Python app as service in Ubuntu with Upstart

I have written a logging application in Python that is meant to start at boot, but I've been unable to start the app with Ubuntu's Upstart init daemon. When run from the terminal with sudo /usr/local/greeenlog/main.pyw, the application works perfectly. Here is what I've tried for the Upstart job:
/etc/init/greeenlog.conf
# greeenlog
description "I log stuff."
start on startup
stop on shutdown
script
exec /usr/local/greeenlog/main.pyw
end script
My application starts one child thread, in case that is important. I've tried the job with the expect fork stanza without any change in the results. I've also tried this with sudo and without the script statements (just a lone exec statement). In all cases, after boot, running status greeenlog returns greeenlog stop/waiting and running start greeenlog returns:
start: Rejected send message, 1 matched rules; type="method_call", sender=":1.61" (uid=1000 pid=2496 comm="start) interface="com.ubuntu.Upstart0_6.Job" member="Start" error name="(unset)" requested_reply=0 destination="com.ubuntu.Upstart" (uid=0 pid=1 comm="/sbin/init"))
Can anyone see what I'm doing wrong? I appreciate any help you can give. Thanks.
Thanks to unutbu's help, I have been able to correct my job. Apparently, these are the only environment variables that Upstart sets (retrieved in Python with os.environ):
{'TERM': 'linux', 'PWD': '/', 'UPSTART_INSTANCE': '', 'UPSTART_JOB': 'greeenlog', 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin'}
My program relies on a couple of these variables being set, so here is the revised job with the right environment variables:
# greeenlog
description "I log stuff."
start on startup
stop on shutdown
env DISPLAY=:0.0
env GTK_RC_FILES=/etc/gtk/gtkrc:/home/greeenguru/.gtkrc-1.2-gnome2
script
exec /usr/local/greeenlog/main.pyw > /tmp/greeenlog.out 2>&1
end script
Thank you!

Categories