-
Using a Loop Inside Your Script: You could modify your script to include an infinite loop, assuming it does not already have one:
# Your code here
-
Using nohup Command: The nohup command allows you to run a process in the background and keeps it running even after the terminal is closed:
nohup python3 ./main.py &
The & at the end sends the process to the background.
-
Using screen or tmux: These terminal multiplexers allow you to create sessions that continue running even when the terminal is closed.
screen -S mysession
python3 ./main.py
Press Ctrl + A, followed by D to detach from the session. Re-attach with screen -r mysession.
-
Using systemd: Create a systemd service to manage your script. Create a file /etc/systemd/system/myscript.service with the following content:
Description=My Python Script
[Service]
ExecStart=/usr/bin/python3 /path/to/main.py
Restart=always
[Install]
WantedBy=multi-user.target
Enable and start the service:
sudo systemctl enable myscript.service
sudo systemctl start myscript.service
-
Using cron with @reboot: Set up a cron job to run your script at boot:
crontab -e
Add the following line:
-
Using Supervisor: Supervisor is a process control system that enables you to monitor and control UNIX-like operating systems' processes:
-
Install Supervisor:
sudo yum install supervisor
-
Create a configuration file for your script /etc/supervisord.d/myscript.ini with the following content:
command=/usr/bin/python3 /path/to/main.py
autostart=true
autorestart=true
stderr_logfile=/var/log/myscript.err.log
stdout_logfile=/var/log/myscript.out.log
-
Reload Supervisor and start your script:
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start myscript
Each of these methods has its own advantages and is suited to different use cases, so you might choose based on your specific needs and environment.