Linux python script autostart

Как установить в автозапуск python-скрипт используя systemd

Иногда требуется какой-то скрипт или программу запускать как системный сервис. Это можно легко провернуть, если в вашем дистрибутиве используется система инициализации и управления демонами — systemd.

Для примера, я создам простейший python-скрипт который будет слушать 9988 порт и добавлю его в автозагрузку при старте операционной системы.

1. Простой python-scrypt

2. Создание файла сервиса.

Теперь создадим файл сервиса для с помощью которого расскажем systemd что нам требуется. Файл должен иметь расширение .service и находиться в директории /lib/systemd/system/

Добавим информацию о нашем сервисе (можете изменить местоположение скрипта и описание сервиса):

Мне кажется из содержимого всё и так понятно — какая строка и за что отвечает.

3. Включение нового добавленного сервиса.

Вы добавили, наконец-то, ваш сервис в систему. теперь необходимо перезапустить демон systemctl чтобы он прочел новый файл. Каждый раз как вы вносите изменения в .service файлы вам нужно перезапустить демон.

Теперь включим запуск сервиса при загрузке системы, и запустим сам сервис.

4. Запуск/Остановка/Статус сервиса

В конце проверим статус нашего нового сервиса:

Проверим что наш python-скрипт слушает нужный нам порт:

Команды для запуска, остановки и перезапуска сервиса:

Источник

Как поставить на автозапуск python скрипт в linux?

Есть запускаю просто из под рута в консоле — всё срабатывает ок. Приложение запускается, всё отрабатывает ок.

Но не понимаю как это поставить на автозапуск (провайдер зачастил ребутать серверы).
Скрипт сервиса:

Лежит в /lib/systemd/system/runapp.service
Скрин статуса:

Заодно подскажите куда как прописать правила iptables так же при старте 🙂
Что читаю и пытаюсь повторить — не работает :\

  • Вопрос задан более двух лет назад
  • 1277 просмотров

1. Вам влом прочитать документацию на инструменты используемые вами
— docs.gunicorn.org/en/stable/deploy.html
2. Вам влом в гугле вбить запрос на поиск методов деплоя используемых вами инструментов
— https://bartsimons.me/gunicorn-as-a-systemd-service/
3. Вам влом изучать операционную систему и её инструменты
— https://habr.com/ru/company/southbridge/blog/255845/
4. Выкиньте нафиг свой скрипт, systemd супервизор и он не занимается запуском скриптиков, а если уж очень хочется то не забывайте про «переменные среды».

Но зато не влом прийти и написать много букав на тостере и при этом даже не удосужились указать операционную систему, конкретную а не общее Linux коих 100500 дистров и у многих свои приколы.

Попробуйте разместить в /etc/systemd/

iptables на разных осях по разному. Создаете скрипт типа:

Источник

Linux python script autostart

Hello,
I have one simple question: Does a Python GUI- script need to be packaged and installed to be ready for autostart when the Raspberry has booted?

There are several methods (rc.local, lxsession, systemd, crontab, …) which I tried with a raw .py script and neither one worked for me. And I could not test it, because after packaging and installing I did not know what would be the file to use for instance for a new crontab-job. I am new to Python and Linux. I would be happy if someone could help me up!
Thanks

Re: Autostart Python script

Languages using left-hand whitespace for syntax are ridiculous

DMs sent on Twitter/LinkedIn will be answered next month.
Fake doctors — are all on my foes list.

Читайте также:  Linux все запущенные сервисы

The use of crystal balls and mind reading is prohibited.

Re: Autostart Python script

Re: Autostart Python script

Re: Autostart Python script

The script does not need to be packaged. Packaging is an advanced procedure that most users would not know how, or have any need to do.

If your python script has been made executable AND has a proper ‘shebang’ as first line then you can start without /usr/bin/python.
First line of your script:

Re: Autostart Python script

I have added to /home/pi/.config/lxsession/LXDE-pi/autostart the line “@/usr/bin/python3 /home/pi/myapp.py”.

Also I have added the shebang “#!/usr/bin/python3” as the first line of the script code.

Also I hope I made the script executable by editing “$ chmod +x myapp.py” in the lxterminal.

So far nothing happens.

However, when I replace “myapp.py” by “lxterminal” in the autostart-file, the lxterminal opens after reboot.
In my original question I mentioned that my app is GUI. Can it be that this is the problem? Or, can it be that my app is running, but in the background?

I found another confusing thing: to test if a script is executable write “./myapp.py” in the terminal. Here I get errors. “Command not found from /var/mail/tkinter” and on other import statements in the script. Also, a syntax error occurs where in the script there is the path to the background graphic. May be, in this case the script still has to be packaged?

I was able to package my script, but I failed to upload to the python test repository (although twain was installed and listed there was a “command not found” error). Therefore I installed locally (assuming that what was supposed to be uploaded and downloaded for installation is the right file to install locally — what is in the dist-folder). Only afterwards I could not find a file or icon to start the app.

Источник

ilyasst / python_systemd.md

Run a python script forever

In this section, we are going to show how to run a python script as a systemd service, allowing you to boot it at the start of a Linux machine and to maintain it alive.

Test method: Telegram Bot

We are going to use a very basic Telegram bot in order to test that our script will:

  1. Automatically start when the machine boot
  2. Automatically restart when it crashes/exits for whichever reason

If the bot is alive, then it means that our method works. Of course, we will also be able to check the status of the service through systemd, but just to be sure . This bot is going to send us

/Temp folder on your Raspberry Pi using SSh
Create a virtual environment in

/Temp, you should already have venv we installed it at the beginning.

    Load the virtual environment: source .env/bin/activate

    Let’s also update pip, and install a pip we need.

    Let’s give our bot:

    Let’s now make this script into a systemd service.

    Important

    All the paths in your scripts have to be absolute paths, there can be no relative path in your scripts. If there are relative paths that you must keep, you will have to change your current working directory by retrieving

    1. Modify the python script, add first line: #!/home/dietpi/Temp/.env/bin/python3 which is the path to the python in the virtual env
    2. chmod +x the python file to make it executable, it will execute with the python you specified (no need to load the venv yourself, just execute without specifying the python bin)
    3. Type the following command in your terminal to add a systemd service sudo systemctl edit —force —full dummy.service :

      Note that ExecStart is the path to the Python file directly if you made it an executable using the right virtual environment. If you did not, then you have to specify a python binary to execute it.

      We have to add an ExecStartPre delay otherwise the service keeps tries to start before internet is even available and we get this error:

    • We also add a Restart flag in order to get systemd to always restart the script if it were to ever fail

    Use Ctrl X + Y to save and exit when you finished editing.

    1. Enable the service sudo systemctl enable dummy.service
    2. Reboot, wait for 30 seconds
    3. Try to contact your bot with /help , All good !
    4. SSH into your RPi
    5. Check your service status: sudo systemctl status dummy.service
    6. Manipulate your service:
    1. Let’s validate that it will really restart on crash. Let’s add a function to our bot that simply kills the script. By killing, I mean that we are going to create an error in order to get the script to crash. When we are working on a telegram bot script, each function is kind of loaded separately, we are going to create an error in a new function and use it to check if the bot truely restarts, add this:

    If you try ths script (in your Virtual Environment not as a service), you will see that the script will return the /help command, but it will simply crash if you try to run the /kill command which tries to print a variable a that was never defined. Because python sees each telegram bot function as a separate function, it does not check that all variables exist before, as a variable can be defined with an incoming Telegram message.

    1. Deploy (copy/paste) this new script on the Raberry pi, then reboot the RPi, so it properly loads as the new systemd service
    2. Wait for 30 seconds, then contact your bot using /help to check that it is online
    3. Use the kill command, the bot should die, wait for a bit more than 10 seconds, as we have a 10 second timer set prior to starting the script
    4. Try /help again, IT WORKS!

    In order to delete the service:

    sudo systemctl disable dummy.service

    Freqtrade on Dietpi

    UPDATE (March 2020)

    The freqtrade code was updated in February 2020 in such a way that freqtrade should now be run from the freqtrade/freqtrade/main.py file instead of freqtrade/bin/freqtrade . This means that there is a difference between the file being edited in the video and the one edited in this document. The version presented in this document should be used.

    In addition, the DefaultStrategy was removed from freqtrade. You will thus get an error if you try to run it, use BBRSI instead.

    /freqtrade/freqtrade , and edit the file called main.py using nano:

  1. Change the first line so that your new file looks like this:
  1. Add the freqtrade systemd service using:
  1. Paste the following:

    Use Ctrl+X then Y followed by Enter to save the new serviced.

    Enable the service sudo systemctl enable freqtrade.service

    Reboot the Raspberry pi: sudo reboot now

    Freqtrade on VM

    UPDATE (March 2020)

    The freqtrade code was updated in February 2020 in such a way that freqtrade should now be run from the freqtrade/freqtrade/main.py file instead of freqtrade/bin/freqtrade . This means that there is a difference between the file being edited in the video and the one edited in this document. The version presented in this document should be used.

    In addition, the DefaultStrategy was removed from freqtrade. You will thus get an error if you try to run it, use BBRSI instead.

    /freqtrade/freqtrade , and edit the file called main.py using nano:

  1. Change the first line so that your new file looks like this:
  1. Add the freqtrade systemd service using:
  1. Paste the following:

    Use Ctrl+X then Y followed by Enter to save the new serviced.

    Источник

    Setup a python script as a service through systemctl/systemd

    There are several ways you can run your program as a background service in Linux such as crontab, .bashrc, etc but today I’ll write about systemd. I was initially looking for a way to run my python script as a background service so even if the server restarts for some reason, my script will run in the background regardless and I found that systemd allows me to do that. Let’s get started

    I’ll be setting this up on an Ubuntu 18.10 machine.

    Almost all versions of Linux come with systemd out of the box, but if your’s didn’t come with it then you can simply run the following command:

    Note: The -y flag means to install the packages and dependencies quickly.

    To check which version of systemd you have simply run the command:

    Create a python file whatever you like. I’m going to call mine test.py.

    sudo nano test.py

    The above script will write the current timestamp in the file after every 10 seconds. Let’s write the service now.

    sudo nano /etc/systemd/system/test.service (name of the service which is test in this case)

    Insert the username in your OS where is written. The ExecStart flag takes in the command that you want to run. So basically the first argument is the python path (in my case it’s python3) and the second argument is the path to the script that needs to be executed. Restart flag is set to always because I want to restart my service if the server gets restarted. For more information on this, you can go to this link. Now we need to reload the daemon.

    Let’s enable our service so that it doesn’t get disabled if the server restarts.

    And now let’ start our service.

    Now our service is up and running.

    Note: The file will be written in the root directory (/) because the program will write in the path from the perspective of systemd. To change that simply edit out the file path. For example:

    There are several commands you can do to start, stop, restart, and check status.

    To stop the service.

    To check status.

    This was a very basic introduction to systemd aimed at beginners who want to get started with writing their own systemd services for python. If you want a deep dive into systemd and systemctl, here is a detailed guide by the digital ocean.

    NOTE: This doesn’t only apply to python scripts. You can basically run any program with this regardless of the programming language your program is written in.

    Источник

    Читайте также:  Драйвера для canon mf3010 windows x64
Оцените статью