Y
Y
yahabrovec2018-09-01 23:48:27
Python
yahabrovec, 2018-09-01 23:48:27

How to run a python script in the background?

Hello everyone
. I'm working on a project here (a personal bot in fact) and the task arose to run it in the background. That is, the process will hang, but the console (command line) will be closed (not minimized). Running the script with an & at the end does not give the desired result. I think that you need to add a couple of lines of code to the script itself.
Tell me who knows

Answer the question

In order to leave comments, you need to log in

4 answer(s)
T
Teslaman, 2018-09-02
@Teslaman

You can write a systemd daemon if your operating system uses it.
Create a daemon file:
Paste the following into it:

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

After that, in the console we execute:
sudo systemctl daemon-reload
sudo systemctl enable bot.service
sudo systemctl start bot.service

To stop the bot:
To remove it from startup: To test the daemon:
sudo systemctl status bot.service

T
trak, 2018-09-02
@trak

Everything has long been invented

N
Nekrasovp, 2018-09-03
@Nekrasovp

By analogy with screen, there is a great option in the form of tmux

V
Vlad Ivanov, 2021-01-05
@vla3d

Script without console window is run via Pythonw.exe instead of Python.exe
Pythonw is associated with .pyw extension
Script runs in the background
5ff4ca128b1f9574985264.jpeg

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question