Auto Start Python Script on Boot (Ubuntu 20.04, Systemd)
NOTE: Use After=network.service if you require network.
Create Bash Script
Create Python Script
Test Systemd
Set file permission
Restart server to test if the service started on reboot
Anaconda
Systemd is run as root by default. If you are using Anaconda (or maybe pyenv ), current user might not run the same python version/environment as root.
NOTE: I tried changing the user via Service.User , but it still uses the system default python interpreter
You can find the python interpreter path using which python or python -c "import sys; print(sys.executable)"
Edit the bash script to use the correct python interpreter
❤️ Is this article helpful?
Buy me a coffee ☕ or support my work via PayPal to keep this space and ad-free.
Do send some to @d_luaz or share this article.
A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz
Travelopy — discover travel places in Malaysia, Singapore, Taiwan, Japan.
Guides Book
Осуществить данную задачу можно двумя путями, первый состоит в том, чтобы записать значение в реестр (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run), здесь подробно описан данный метод. Однако при этом нам будет необходимо разрешение на запись в реестр, и чтобы его получить придется постараться.
Второй путь проще и не требует особых привилегий программе, для этого необходимо создать ярлык программы в C:\Users\UserName\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup (путь для Windows 7).
Ниже показан код, позволяющий это сделать, при этом создается ярлык на исполняемый файл и сохраняется в выше указанную папку, и при желании его от туда можно убрать.
В коде использован пакет winshell, позволяющий получать доступ к специальным папкам Windows.
How to Run Python Script at Startup in Ubuntu
The reputation of Python as a programming language speaks for itself. This programming language is attributed as general-purpose, high level, and interpreted.
Most Linux users are in love with the Python programming language due to its code readability which makes it easy to follow and master even for a beginner in the programming world.
Some advantages of Python Programming language are listed below:
- Open-source and community development support.
- Rich in third-party modules.
- User-friendly data structures.
- Dynamically typed programming language.
- Interpreted language.
- Highly efficient.
- Portable and interactive.
- Extensive libraries support.
The above-mentioned features make Python ideal for projects related to software development (desktop, web, gaming, scientific, image processing, and graphic design applications), operating systems, database access, prototyping, and language development.
This article will address the use of Python as a scripting language in an operating system environment (Ubuntu).
Prerequisites
Ensure you meet the following requirements:
- You are a sudoer/root user on a Linux operating system distribution.
- You can comfortably interact with the Linux command-line environment, interpret, and execute its associated commands.
- You have the latest version of Python installed on Ubuntu.
Confirm that you have Python installed by running the command:
Running a Python Script at Startup in Ubuntu
The following steps will help us achieve the main objective of this article.
Step 1: Create Your Python Script
Create your Python script if it does not already exist. For this article guide purpose, we will create and use the following Python script.
Add the following Python script.
Upon rebooting our Ubuntu system, the above Python script should be able to create a file called i_was_created.txt on the Ubuntu Desktop (Desktop). Inside this file, we should find the text This LinuxShellTips Tutorial Actually worked! together with the date and time of its creation.
Next, move the Python Script to a directory where it can be executed with root user privileges upon system restart. One such viable directory, in this case, is /bin.
Let us move the script using the mv command.
Now create a cron job scheduler that will periodically handle the execution of the above-created Python script (In this case during system startup).
At the bottom of this file, add the line:
Save and close the file and then confirm the creation of the cron job schedule:

Check Cron Job in Linux
The @reboot portion of the above line tells the cron job scheduler to execute the script at system startup. The & parameter informs the cron job scheduler to execute the Python script in the background so as not to interfere with normal system startup.
We are now ready to reboot our system
Let us check if our file was created:

Run Python Script at Ubuntu Startup
The existence of the above file confirms the Python script was successfully executed at the Ubuntu system startup.
Как добавить код python в автозагрузку
Все работает, но хотелось бы чтобы этот скрипт запускался сам при включении распберри пи.
Помогите советом как это сделать плиз[/quote]
Есть несколько способов поставить в автозагрузку на выбор:
1.Если у тебя стартуют иксы то тогда проще в /etc/xdg/autostart создать выражаясь терминологиями M$ ярлык на файлик
Re: скрипт python в автозапуск
Re: скрипт python в автозапуск
Re: скрипт python в автозапуск
Re: скрипт python в автозапуск
Друзья, прошу помочь!
Пишу скрипт на python, использована предложенном решение, прописал его в автозапуск. Проблема в том, что я не использую GUI и стартует оболочка только после ввода startx, а мой скрипт почему-то не хочет работать до запуска GUI.
Подскажите пожалуйста, куда мне копать?
Re: скрипт python в автозапуск
Re: скрипт python в автозапуск
Нужно, чтобы скрипт запускался при загрузке малинки, не дожидаясь запуска GUI.
Я новичек и в линуксе и в пайтоне, и не понимаю, почему моя программа работает только после ввода startx в консоли.
Re: скрипт python в автозапуск
Добро пожаловать в линукс)
При надобности, в линуксе можно управлять последовательностью автозагрузки.
Для этого нужно прописать свой скрипт в загрузку командой:
sudo update-rc.d имя_скрипта defaults
А можно тупо по старинке прописать свой скрипт в /etc/rc.local перед «exit 0»
Если пусть нестандартный, то прописывать полностью.
А файлы «имя.desktop» с прописанным в нутри «Exec=/путь/мой_скрипт» в
/.config/autostart
запускаются десктопным менеджером, в данном случае LXDE, у openbox-a другая система автостарта.
Re: скрипт python в автозапуск
Re: скрипт python в автозапуск
К сожалению, пока не решил свою проблему. Вернее, обнаружил ее причину, но как решать — не знаю:(
Я прописал программу в автозагрузку, но она не стала запускаться, ругаясь на невозможность загрузки некоторых модулей (см. скрин: https://yadi.sk/i/fZkOreh3Vsmfn )
Подскажите пожалуйста, что я делаю не так?
Re: скрипт python в автозапуск
Re: скрипт python в автозапуск
Спасибо всем за Ваши советы!
Проблема крылась где-то в недрах моей программы — так я и не понял где. Скорее всего это действительно какие-то артефакты в коде.
Запустить программу без компилятора так и не получилось, а вот новый скрипт с одной строкой вызова моей основной программы система приняла. Т. ч. все заработало!
Помимо этого, Вы помогли мне немного разобраться в линухе, дав направление, где мне копать. Еще раз спасибо Вам всем за Вашу помощь!
Re: скрипт python в автозапуск
Всем доброго времени суток!
Пишу небольшой скрипт на python, с котором хотелось бы общаться через терминал. Затем добавил его в автозагрузку.
При запуске Raspbian после запуска рабочего стола мой скрипт выполняется 2 раза подряд (есть запись в log файле). Причем при первом запуске он не открывает терминал, а при втором запуске- открывает терминал.
Здесь привел условный пример скрипта, загружающий одно ядро на 100%
С raspberry работаю через VNC терминал. Если послать команду CTRL+ALT+DEL, то в списке процессов есть 2 Команды: python, каждый с загрузкой системы по 25%, что логично с учётом скрипта
Собственно вопрос: почему так происходит и как сделать что-бы скрипт запускался один раз?