2

I'm trying to make a Python script run as a service.

It need to work and run automatically after a reboot. I have tried to copy it inside the init.d folder, But without any luck.

Can anyone help?(if it demands a cronjob, i haven't configured one before, so i would be glad if you could write how to do it)

(Running Centos)

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Idan Shuster
  • 63
  • 1
  • 2

3 Answers3

9

run this command

crontab -e

and then add

@reboot /usr/bin/python /path/to/yourpythonscript

save and quit,then your python script will automatically run after you reboot

ramsay
  • 3,197
  • 2
  • 14
  • 13
0

There is no intrinsic reason why Python should be different from any other scripting language here.

Here is someone else using python in init.d: blog.scphillips.com/posts/2013/07/… In fact, that deals with a lot that I don't deal with here, so I recommend just following that post.

Max Murphy
  • 1,701
  • 1
  • 19
  • 29
  • Here is someone else using python in init.d: http://blog.scphillips.com/posts/2013/07/getting-a-python-script-to-run-in-the-background-as-a-service-on-boot/ In fact, that deals with a lot that I don't deal with here, so I recommend just following that post. – Max Murphy Jan 15 '17 at 15:42
0

For Ubuntu Variant:- open the /etc/rc.local file with:

nano /etc/rc.local

add the following line just before the exit 0 line:

start-stop-daemon -b -S -x python /root/python/test.py

or

Give absolute path of your command i.e

nohup /usr/bin/python2 /home/kamran/auto_run_py_script_1.py &

The start-stop-daemon command creates a daemon to handle the execution of our program. The -b switch causes the program to be executed in the background. The -S switch tells the daemon to start our program. And the -x switch tells the daemon that our program is an executable.

To check and Run

sudo sh /etc/rc.local
kamran kausar
  • 4,117
  • 1
  • 23
  • 17