Python запустить функцию в фоне

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:

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:

Читайте также:  Dataset python power bi

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 Asyncio Coroutine in the Background

You can wrap a coroutine in an asyncio.Task which will schedule it for later execution.

This allows you to run coroutines in the background that do not block the caller.

In this tutorial, you will discover how to run a coroutine in the background as an asyncio task.

Need to Run a Background Coroutine

When running a coroutine from a coroutine within asyncio, it blocks the caller.

That is, it suspends the caller until the other coroutine is complete.

We may need to execute a coroutine in the background.

That is, schedule the coroutine for execution and have it run as soon as it is able, but not explicitly suspend the calling coroutine.

How can we run a coroutine in the background in asyncio?

Run your loops using all CPUs, download my FREE book to learn how.

How to Run a Background Coroutine

We can run a coroutine in the background by wrapping it in an asyncio.Task object.

This can be achieved by calling the asyncio.create_task() function and passing it the coroutine.

The coroutine will be wrapped in a Task object and will be scheduled for execution. The task object will be returned and the caller will not suspend.

You can learn more about how to create tasks in the tutorial:

The task will not begin executing until at least the current coroutine is suspended, for any reason.

We can help things along by suspending for a moment to allow the task to start running.

This can be achieved by sleeping for zero seconds.

This will suspend the caller only for a brief moment and allow the ask an opportunity to run.

This is not required as the caller may suspend at some future time or terminate as part of normal execution.

You can learn more about sleeping in the tutorial:

We may also await the task directly once the caller has run out of things to do.

Now that we know how to run a coroutine in the background as a task, let’s look at some worked examples.

Confused by the asyncio module API?
Download my FREE PDF cheat sheet

Example of Running a Foreground Task

Before we look at how to run a coroutine as a task in the background, let’s review how we might run it in the foreground.

That is, we can call a coroutine directly and have it suspend the caller.

The example below defines a custom coroutine and calls that coroutine from the main coroutine.

The main coroutine will block until the called coroutine is complete.

Note, we are not calling the coroutine per se, we are scheduling it for executing and waiting for it to complete, e.g. await it.

The complete example is listed below.

Running the example first creates the main() coroutine and uses it as the entry point for the asyncio program.

The main() coroutine runs and creates the custom_coro(). It then awaits this new coroutine.

This suspends the main() coroutine and schedules the custom_coro() coroutine.

The custom_coro() runs, reports a message, sleeps, then reports a final message before terminating.

The main() coroutine then resumes and closes the program.

This highlights how a coroutine can be executed in a way that blocks the caller, e.g. in the foreground of a coroutine.

Next, let’s explore how we might run a coroutine in the background as a task.

Free Python Asyncio Course

Download my asyncio API cheat sheet and as a bonus you will get FREE access to my 7-day email course on asyncio.

Discover how to use the Python asyncio module including how to define, create, and run new coroutines and how to use non-blocking I/O.

Example of Running a Background Task

We can run a coroutine in the background as a task.

Specifically, we can have the coroutine wrapped in an asyncio.Task and have it scheduled for execution as soon as it can.

The example below creates a custom coroutine from the main coroutine and schedules it for execution as a task. It then sleeps for a moment to allow the task to begin executing, then sleeps for a longer time to simulate doing other work.

The complete example of running a coroutine as a background task is listed below.

Running the example first creates the main() coroutine and uses it as the entry point for the asyncio program.

The main() coroutine runs and creates the custom_coro().

It then wraps the coroutine in an asyncio.Task and schedules it for execution.

The main() coroutine then sleeps for zero seconds. This suspends the caller and allows the scheduled coroutine to execute.

The custom_coro() coroutine executes, reporting a message and then suspending with a sleep.

The main() coroutine resumes, reports a message then sleeps to simulate doing other work.

The custom_coro() completes its sleep, resumes, reports a final message then terminates.

The main() coroutine finishes its sleep, resumes and the program is terminated.

This example highlights how we can run a coroutine in the background as a task.

Источник

Как запустить 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'

Источник

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