Запустить python скрипт фоном

Запуск Python скрипта в виде службы через systemctl/systemd

Есть несколько способов запуска вашей программы в качестве фоновой службы в Linux, таких как crontab, .bashrc и т. д., но сегодня будет разговор о systemd. Изначально я искал способ запустить свой скрипт на Python в качестве фоновой службы, поэтому даже если сервер по какой-то причине перезагрузится, мой скрипт все равно должен работать в фоновом режиме, после небольшого ресерча и я обнаружил, что systemd позволяет мне это сделать. Давайте начнем.

Настройки далее будут производиться на машине с Ubuntu 20.04.

Почти все версии Linux поставляются с systemd из коробки, но если у вас его нет, вы можете просто запустить следующую команду:

sudo apt install -y systemd 

Примечание. Флаг -y означает быструю установку пакетов и зависимостей.

Чтобы проверить, какая версия systemd у вас установлена, просто выполните команду:

Создайте файл python с любым именем. Я назову свой скрипт именем test.py.

import time from datetime import datetime while True: with open("timestamp.txt", "a") as f: f.write("Текущая временная метка: " + str(datetime.now())) f.close() time.sleep(10) 

Приведенный выше скрипт будет записывать текущую метку времени в файл каждые 10 секунд. Теперь напишем сервис.

sudo nano /etc/systemd/system/test.service 

(имя службы, которая тестируется в этом случае)

[Unit] Description=My test service After=multi-user.target [Service] User=deepak Group=admin Type=simple Restart=always ExecStart=/usr/bin/python3 /home//test.py [Install] WantedBy=multi-user.target 

Замените имя пользователя в вашей ОС, где написано . Флаг ExecStart принимает команду, которую вы хотите запустить. Таким образом, в основном первый аргумент — это путь к python (в моем случае это python3), а второй аргумент — это путь к скрипту, который необходимо выполнить. Флаг перезапуска всегда установлен, потому что я хочу перезапустить свою службу, если сервер будет перезапущен.

Здесь мы определили User=deepak и Group=admin, чтобы убедиться, что скрипт будет выполняться только от имени пользователя deepak, входящего в группу admin.

Теперь нам нужно перезагрузить демон.

sudo systemctl daemon-reload 

Давайте включим наш сервис, чтобы он не отключался при перезагрузке сервера.

sudo systemctl enable test.service 

А теперь давайте запустим наш сервис.

sudo systemctl start test.service 

Теперь наш сервис работает.

Примечание. Файл будет записан в корневой каталог (/), потому что программа запишет путь с точки зрения systemd. Чтобы изменить это, просто отредактируйте путь к файлу. Например:

import time from datetime import datetime path_to_file = "введите желаемый путь к файлу" while True: with open(path_to_file, "a") as f: f.write("Текущая временная метка: " + str(datetime.now())) f.close() time.sleep(10) 

Есть несколько команд, которые вы можете выполнить для запуска, остановки, перезапуска и проверки состояния.

sudo systemctl stop name_of_your_service 
sudo systemctl restart name_of_your_service 
sudo systemctl status name_of_your_service 

Это было очень поверхностное знакомство с systemd, предназначенное для новичков, которые хотят начать писать свои собственные systemd службы для python.

Читайте также:  Заголовок страницы

ПРИМЕЧАНИЕ. Это относится не только к сценариям Python. Вы можете запустить любую программу с ним, независимо от языка программирования, на котором написана ваша программа.

Источник

Как запустить python скрипт в фоновом режиме?

Я тут работаю над одним проектом(личный бот по факту) и возникла задача запустить его в фоне. То есть процесс будет висеть , но консоль(командная строка) будет закрыта(не свернута). Запуск скрипта с добавлением в конец & — не дает нужного результата. Думаю что нужно добавить пару строчек кода в сам скрипт.
Подскажите кто знает

Можно написать демон для systemd если в вашей операционной системе он используется.

Создаём файл демона:
sudo touch /etc/systemd/system/bot.service

[Unit] Description=My bot After=multi-user.target [Service] Type=idle ExecStart=/usr/bin/python /путь/до/скрипта/bot.py Restart=always [Install] WantedBy=multi-user.target

После этого в консоли выполяем:

sudo systemctl daemon-reload sudo systemctl enable bot.service sudo systemctl start bot.service

Чтобы остановить бот:
sudo systemctl stop bot.service
Чтобы удалить из автозагрузки:
sudo systemctl disable bot.service
Чтобы проверить работу демона:
sudo systemctl status bot.service

yahabrovec, тю. С этого и нужно было начинать 🙂

Как это делается в винде я не знаю.

trec

Автору ответа большое спасибо, ответ помог настроить скрипт.
Я же добавлю свою настройку для запуска скрипта из окружения

Суть: у меня проект юзает pipenv и надо было его запускать из окружения. В целом не суть важно через что у вас создается окружение, настроить запуск скрипта из окружения возможно следующими шагами.
1) залейте проект на сервак (/home/myuser/tel-bot)
2) ставьте окружение, узнайте полный путь к питоноу вашего окружения (/home/myuser/.local/share/virtualenvs/tel-bot-31zbdxgR/bin/python)
3) запускаем скрипт из окружения: ExecStart=/bin/bash -c ‘cd /home/myuser/tel-bot && /home/myuser/.local/share/virtualenvs/tel-bot-31zbdxgR/bin/python run.py’

Вот полный конфиг systemd:

[Unit] Description=super puper bot After=multi-user.target [Service] Type=idle ExecStart=/bin/bash -c 'cd /home/myuser/tel-bot && /home/myuser/.local/share/virtualenvs/tel-bot-31zbdxgR/bin/python run.py' Restart=always [Install] WantedBy=multi-user.target

Дмитрий, а если сперва надо перейти в каталог питон проекта а после запустить main.py как будет выглядеть команда?

ExecStart=/bin/bash -c ‘cd /home/myuser/scrypt && /usr/bin/python3 main.py’

trec

ExecStart=/bin/bash -c 'cd /home/myuser/tel-bot && /home/myuser/.local/share/virtualenvs/tel-bot-31zbdxgR/bin/python run.py'

то при остановке или перезагрузки службы, у меня скрипт не отрабатывал до конца (как это было при завершении обычной работы скрипта [ctrl + C])
Первую команду из ExecStart можно убрать. Просто в той же секции [Service] пишем:
WorkingDirectory=/home/myuser/tel-bot

В итоге скрипт норм завершается, получаем:

WorkingDirectory=/home/myuser/tel-bot ExecStart=/bin/bash -c '/home/myuser/.local/share/virtualenvs/tel-bot-31zbdxgR/bin/python run.py'

Источник

Running a Python Script in the Background

This is a quick little guide on how to run a Python script in the background in Linux.

Make Python Script Executable

First, you need to add a shebang line in the Python script which looks like the following:

This path is necessary if you have multiple versions of Python installed and /usr/bin/env will ensure that the first Python interpreter in your $PATH environment variable is taken. You can also hardcode the path of your Python interpreter (e.g. #!/usr/bin/python3 ), but this is not flexible and not portable on other machines. Next, you’ll need to set the permissions of the file to allow execution:

Start Python Script in Background

Now you can run the script with nohup which ignores the hangup signal. This means that you can close the terminal without stopping the execution. Also, don’t forget to add & so the script runs in the background:

Читайте также:  Php include path phpstorm

If you did not add a shebang to the file you can instead run the script with this command:

nohup python /path/to/test.py & 

The output will be saved in the nohup.out file, unless you specify the output file like here:

nohup /path/to/test.py > output.log & nohup python /path/to/test.py > output.log & 

Find and Kill the Running Process

You can find the process and its process Id with this command:

If you want to stop the execution, you can kill it with the kill command:

It is also possible to kill the process by using pkill, but make sure you check if there is not a different script running with the same name:

Output Buffering

If you check the output file nohup.out during execution you might notice that the outputs are not written into this file until the execution is finished. This happens because of output buffering. If you add the -u flag you can avoid output buffering like this:

Or by specifying a log file:

nohup python -u ./test.py > output.log & 

Источник

How To Run Python Script Constantly In Background

In this article, you will learn to run Python Script Constantly in the Background. I’ll show you a variety of methods for keeping Python scripts running in the background on various platforms.

The Python scripting language (files with the extension.py) is run by the python.exe program by default. This application launches a terminal window, which remains open even if the program utilizes a graphical user interface (GUI).

If you do not want this to happen, use the extension.pyw, which will cause the script to be executed by pythonw.exe by default. This prevents the terminal window from appearing when the computer is first booted.

Let us see in the below example codes how you can run Python Script Constantly In Background.

1. Using sched To Run Python Script Constantly In Background

In Python, you have a library named sched [1] that acts as a Scheduler and allows you to run a script or program in Python continuously. Events can be scheduled using the scheduler class’s generic interface. When it comes to dealing with the “outside world,” two functions are needed: timefunc, which is callable without parameters and returns a number.

Let us see in the below example code the usage of sched to run Python script constantly.

import sched import time schedulerTest = sched.scheduler(time.time, time.sleep) def randomFunc(test = 'default'): print("Testing Scheduler to Run Script Constantly.") schedulerTest.enter(30, 1, randomFunc, ('checkThis',)) schedulerTest.enter(30, 1, randomFunc, ('TestThis',)) schedulerTest.run()
Testing Scheduler to Run Script Constantly. Testing Scheduler to Run Script Constantly.

If you are going to use the above code, and add the function that you want to run constantly then you can use the scheduler library.

2. Using the time.sleep() Function To Run Script repeatedly

So, if you do not want to use the above code and just want to run your script repeatedly then you can use the time.sleep() function. This function allows your script to keep running after sleeping for a certain amount of time.

Читайте также:  Multipart form data java spring

Let see in the below example code the usage of time.sleep() function to run Python Script Repeatedly.

import time while True: def randomFunctionYouWantToKeepRunning(): print("Testing To Run Script in Background Every 10 secs.") randomFunctionYouWantToKeepRunning() time.sleep(10)
Testing To Run Script in Background Every 10 secs. Testing To Run Script in Background Every 10 secs.

As you can see using the above code, I was able to run the script constantly after every 10 seconds. Based on your usage and after how much time you want the program to re-run you can change the time and then re-run the script.

How To Run Python Script In Background In Linux

You can use the below code on your terminal command line to run the Python Script in the background in Linux. You can also use the code described above to run the Python script constantly.

First, add a Shebang line in your Python Script using the below code.

If you have numerous versions of Python installed, this path is required to ensure that the first Python interpreter listed in your $$PATH environment variable is taken into consideration. Your Python interpreter’s location can alternatively be hardcoded, although this is less flexible and less able to be used on different machines.

Now run the below command to make the Shebang executable.

chmod +x yourPythonScriptName.py

If you use no hangup, the application will continue to execute in the background even if your terminal is closed.

nohup /path/to/yourPythonScriptName.py & or nohup python /path/to/test.py &

Here & is used as this will tell the operating system to put this process to run in the background.

How To Run Python Script In Background In Windows

If you want to run any Python script in Background in Windows operating System then all you are required to do is to rename the extension of your existing Python script that you want to run in background to ‘.pyw’.

Once you have re-named it then you can run the Python Script and it will start executing in the background. To Terminate the program that started running in the background you will require to use the below command.

Wrap Up

I hope you got your answer and learned about how to run Python Scripts Constantly In the Background Of Windows, Linux or MacOS. I have discussed two methods and you can use any two methods that work perfectly for you.

Let me know in the comment section if you know any better method than the one discussed above, I will be happy to add it here. Also, let me know if you have any issues related to the above code.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Источник

Оцените статью