[python] Run Python script at startup in Ubuntu

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.)

This question is related to python linux shell ubuntu

The answer is


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 !!

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.


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!


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


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


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to ubuntu

grep's at sign caught as whitespace "E: Unable to locate package python-pip" on Ubuntu 18.04 How to Install pip for python 3.7 on Ubuntu 18? "Repository does not have a release file" error ping: google.com: Temporary failure in name resolution How to install JDK 11 under Ubuntu? How to upgrade Python version to 3.7? Issue in installing php7.2-mcrypt Install Qt on Ubuntu Failed to start mongod.service: Unit mongod.service not found