Linux How to run python script on startup

5

1

Linux Ubuntu 14.04 Have a script in ~/app/serve.py

Need to run it in this folder. In shell I may do

> cd ~/app && python serve.py

and it runs a server

Need to run it on servers boot in background. Tried to add this command cd ~/app && python serve.py ~ in etc/rc.local (and etc/init.d/rc.local) but it doesn't start.

What am I doing wrong?

WHITECOLOR

Posted 2016-08-10T22:22:27.670

Reputation: 347

Answers

5

Instead of adding cd ~/app && python serve.py in /etc/rc.local, try putting in the entire path. You are expecting the init process to know that ~ is your home directory somehow, but init starts as root. Because init starts as root, it's looking in / for the app directory not your home directory. Get rid of the ~ by using the path to your home directory.

Try adding /home/whitecolor/app/serve.py to /etc/rc.local. (pwd to find your pathway directory.) Get rid of the python in front of your serve.py script by adding #!/usr/bin/python at the top of your script. (type a which python to find the path in case it isn't installed in the normal place)

Edit: You did say "run in the background", and I missed that. To run a command in the background, add a & after the command. So, to background that command above: /home/whitecolor/app/serve.py & Init doesn't usually need the background symbol to start a job and run it in the background.

DrDR's excellent suggestion would not need the same & treatment after the command in the cron startup as those are run in the background by default.

ScotT

Posted 2016-08-10T22:22:27.670

Reputation: 191

Yes you are correct, I needed to replace ~ with needed user home. Thank you very much) – WHITECOLOR – 2016-08-11T00:10:32.247

4

I've never had the need to try this, but apparently scripts can be run at system startup via cron by adding a line similar to the one beginning with @reboot below.

#m  h  dom  mon  dow  command
1   *  *    *    *    someHourlyCommand
@reboot               python /home/<username>/app/serve.py

Note, I've changed the command slightly to eliminate cd'ing into the directory. Your situation may be different, so do what works for you.

DrDR

Posted 2016-08-10T22:22:27.670

Reputation: 311

1

I believe it is @reboot, not @startup, see here, http://linux.die.net/man/5/crontab under Extensions.

– MariusMatutiae – 2016-08-12T10:07:49.973

Thanks for the correction, MariusMatutiae. I've edited my answer accordingly. – DrDR – 2016-09-16T16:24:14.683