Answer the question
In order to leave comments, you need to log in
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
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
sudo systemctl daemon-reload
sudo systemctl enable bot.service
sudo systemctl start bot.service
sudo systemctl status bot.service
By analogy with screen, there is a great option in the form of tmux
Script without console window is run via Pythonw.exe instead of Python.exe
Pythonw is associated with .pyw extension
Script runs in the background
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question