简体   繁体   中英

Autostart Python script and run in background with Ubuntu

I'm running Ubuntu server 16.04 and still getting to grips with it. I have a python script that runs in an endless loop, performing a task related to fetching data from an external source.

What I'm trying to do, is make this python script start after (or during) boot and then run in the background.

I've tried editing rc.local but the boot sequence just hangs since the script keeps running.

Any advice would be greatly appreciated.

tmux is a great utility for background desktops. You can use it for this:

sudo apt get install tmux

Then add it to your rc.local:

/usr/bin/tmux new-session -d 'python /path/to/your/script'

After boot you can use it as follow:

tmux attach

And your console will be attached to the last desktop working at background.

As one of the comments mentions, you can use cronjobs to start scripts at certain times such as at startup(as you would like to do). It also would not halt execution like you mentioned with rc.local

The line that you need to add to the chronjob list is -

@reboot python /home/MyPythonScript.py

Here is are a couple of useful tutorials that show you how to do this: http://kvz.io/blog/2007/07/29/schedule-tasks-on-linux-using-crontab/ https://help.ubuntu.com/community/CronHowto

If you would like to do it with python itself there is this handy python library - https://pypi.python.org/pypi/python-crontab/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM