79

I have a short Python script that needs to run at startup - Ubuntu 13.10. I have tried everything I can think of but can't get it to run. The script:

#!/usr/bin/python
import time
with open("/home/username/Desktop/startup.txt", 'a') as f:
    f.write(str(time.time()) + " It worked!")

(The actual script is a bit different, as I'm just using this for testing purposes, but you get the idea.)

I've tried all of the following, with no luck:

  • Put the command python startuptest.py in crontab, as @reboot python /home/username/Documents/startuptest.py, both as the regular user and as sudo

  • Put the command python /home/username/Documents/startuptest.py in /etc/rc.local

  • Opened Ubuntu's Startup Applications and put the command there

  • Done all of the preceding, putting the command into a shell script and calling that shell script instead

Nothing works. I get the feeling I'm missing something simple. Any ideas? (The script runs fine if I just run the command from a terminal.)

crypto
  • 933
  • 1
  • 8
  • 7
  • On /etc/rc.local, did you try to give the full python path there? And add a simple '/usr/bin/date >> /tmp/date.stamp' to rc.local for checking if the script is run. – TeTeT Jul 01 '14 at 20:19
  • 1
    Can you verify rc.local has +x privileges? What happens if you just try and run /etc/rc.local after startup with the Python script included? – Matt Jul 01 '14 at 20:19
  • 1
    with `crontab` you don't get your environment setup so it probably can't find `python` try qualifying `python` using the whole path `/usr/bin/python` or similar – Robert Ekendahl Jul 01 '14 at 20:24
  • rc.local has +x privileges; if I run it after startup the scripts runs. Still no dice on startup, though. – crypto Jul 01 '14 at 20:54
  • 1
    Robert - using /usr/bin/python in crontab seems to work. Thank you! – crypto Jul 01 '14 at 20:56
  • Try this https://stackoverflow.com/questions/36831433/django-server-autorun-when-ubuntu-startup-or-reboot – nomi Oct 23 '19 at 18:55

6 Answers6

56

Instructions

  • Copy the python file to /bin:

    sudo cp -i /path/to/your_script.py /bin

  • Add A New Cron Job:

    sudo crontab -e

    Scroll to the bottom and add the following line (after all the #'s):

    @reboot python /bin/your_script.py &

    The “&” at the end of the line means the command is run in the background and it won’t stop the system booting up.

  • Test it:

    sudo reboot

Practical example:

  • Add this file to your Desktop: test_code.py (run it to check that it works for you)

    from os.path import expanduser
    import datetime
    
    file = open(expanduser("~") + '/Desktop/HERE.txt', 'w')
    file.write("It worked!\n" + str(datetime.datetime.now()))
    file.close()
    
  • Run the following commands:

    sudo cp -i ~/Desktop/test_code.py /bin

    sudo crontab -e

  • Add the following line and save it:

    @reboot python /bin/test_code.py &

  • Now reboot your computer and you should find a new file on your Desktop: HERE.txt

João Cartucho
  • 3,688
  • 32
  • 39
  • Is `/bin` the only place where a python script can be run? – Johan Dettmar Nov 17 '19 at 22:40
  • It needs to be in a directory where scripts run as root when the system starts. So for example inside `/boot` or `/etc` ... should also work. – João Cartucho Nov 20 '19 at 10:28
  • I think https://stackoverflow.com/a/25805612/1964109 is simpler and more elegant. Using crontab feels so 2000. – Max N Dec 20 '19 at 11:09
  • 1
    @MaxN yeah, you are right. Anyway, crontab has some really nice features as, for example, you can make the script run at specific times. – João Cartucho Dec 23 '19 at 13:24
  • When using `crontab -e`, the file gets saved in `/tmp` folder. Is that normal? Shouldn't such a file be saved in a more reliable folder like `/usr` or `/home` or `/etc` or `/opt`? Why is it stored in `/tmp`? It's not some temporary file that I'm creating. Couldn't it be saved in some other folder? – Nav May 08 '23 at 15:50
  • @Nav the file gets saved at `/var/spool/cron/crontabs`. The crontab file is not meant to be edited directly but through the crontab command using the `-e` option. Also if you don't use `sudo` to edit the crontab file, you will be editing the file for the current user, not the root user. This means that any commands added to the crontab file will only be executed as that user, not as the root user. – João Cartucho May 11 '23 at 06:54
37

Put this in /etc/init (Use /etc/systemd in Ubuntu 15.x)

mystartupscript.conf

start on runlevel [2345]
stop on runlevel [!2345]

exec /path/to/script.py

By placing this conf file there you hook into ubuntu's upstart service that runs services on startup.

manual starting/stopping is done with sudo service mystartupscript start and sudo service mystartupscript stop

kame
  • 20,848
  • 33
  • 104
  • 159
RickyA
  • 15,465
  • 5
  • 71
  • 95
  • 9
    mystartupscript.conf: unrecognized service – ProGirlXOXO Feb 26 '16 at 10:15
  • 1
    @ProGirlXOXO Ubuntu 15.x switched from /etc/init to /etc/systemd – kame May 05 '16 at 06:46
  • it is really helpful ..bt stop is not working ....when i was doing ==>sudo service startpy stop ...it is giving me an error like this ===> stop: Unknown instance: .... can u tell me what is the problem?? – Sudip Das Nov 03 '16 at 22:04
  • @SudipDas then it was not running. Either it completed ok on its own, or there is an error in the startup script that prevents it from running. Logfiles are at `/var/log/upstart/[servicename]`. Or you can run the command after `exec` in a terminal to see what happens. – RickyA Nov 04 '16 at 08:57
  • This solution is not working for me, but the one using crontab did work! I am using Ubuntu 14.04. – lfvv May 31 '17 at 17:41
  • 2
    I got this error: Failed to start mystartupscript.service: Unit notifyIP.service not found. – Clock ZHONG Dec 11 '17 at 14:57
  • Error: Failed to start mystartupscript.service: Unit startup_peter.service not found – PeterN Nov 16 '20 at 15:42
22

If you are on Ubuntu you don't need to write any other code except your Python file's code , Here are the Steps :-

  • Open Dash (The First Icon In Sidebar).
  • Then type Startup Applications and open that app.
  • Here Click the Add Button on the right.
  • There fill in the details and in the command area browse for your Python File and click Ok.
  • Test it by Restarting System . Done . Enjoy !!
Aditya Agarwal
  • 753
  • 6
  • 6
  • 2
    by far the best method on ubuntu – paddyg Jul 29 '18 at 21:59
  • 4
    What if the python script is running on virtualenv ? ie ; if you have to activate virutualenv before running the script ? – Anoop D Sep 06 '18 at 02:55
  • In Lubuntu I had to add `python /path/to/script.py &` to the `Default Applications in LXSession`. The `&` is running the script in background. Check if running with `ps ax | grep python`. – bomben Jan 28 '20 at 07:41
  • although, if sudo is required, it might not work – mmmmmm Oct 10 '21 at 13:29
13

Create file ~/.config/autostart/MyScript.desktop with

[Desktop Entry]
Encoding=UTF-8
Name=MyScript
Comment=MyScript
Icon=gnome-info
Exec=python /home/your_path/script.py
Terminal=false
Type=Application
Categories=

X-GNOME-Autostart-enabled=true
X-GNOME-Autostart-Delay=0

It helps me!

id614515
  • 187
  • 1
  • 4
  • I tried this in Ubuntu it was working perfectly but I tried it in orange Pi it is not working. There was no ~/.config/autostart/ directory. I created first and did same as mentioned above but it did not work. Any solution – Imran Jun 23 '21 at 12:16
  • 1
    The "autostart" directory in .config does not exist on my ubuntu system. Ubuntu 18.04.5 LTS (Bionic Beaver) – cheesus Jul 09 '21 at 09:30
  • @cheesus I wonder if `apt install gnome-tweaks` would create it for you? I'm also on 18.04 and I do have the folder which contains a couple `*.desktop` files which I know I added through the Tweaks GUI as startup applications – Addison Klinke Jan 26 '22 at 15:02
  • Similar end result as @Aditya Argawal's answer above, just via the CLI instead of GUI – Addison Klinke Jan 26 '22 at 15:08
2

nano /etc/rc.local

and edit in

python ~/path-to-script.py

worked for me

Mike
  • 70
  • 6
1

In similar situations, I've done well by putting something like the following into /etc/rc.local:

cd /path/to/my/script
./my_script.py &
cd -
echo `date +%Y-%b-%d_%H:%M:%S` > /tmp/ran_rc_local  # check that rc.local ran

This has worked on multiple versions of Fedora and on Ubuntu 14.04 LTS, for both python and perl scripts.

jazcap53
  • 381
  • 5
  • 17
  • I have tried the method here posted by jazcap53 as well as a version of the one here by RickyA and another one in which I modified the /etc/rc.local file. My pyhton script works to create the HERE.txt file but in none of these cases does it make that file on reboot. – SteveC Mar 04 '20 at 17:41