SoFunction
Updated on 2025-04-28

Detailed explanation of how to restart python scripts in Windows automatically

The blogger encountered a requirement: I need to restart a python script regularly every day. This script runs on a Windows computer. Here is the blogger's solution:

  • Get the ID of the started application
  • This application ID kill
  • Run this script again according to the specified Python environment

Solution steps

1. Get the started application ID

The blogger's program will listen to port 5001, so based on this feature, run the following code to obtain the startup application ID:

import os
import subprocess
import time
from loguru import logger


def exec_cmd(cmd):
    """Execute commands and results"""
    r = (cmd)
    text = ()
    ()
    return text

cmd = "netstat -aon|findstr 5001"
result = exec_cmd(cmd).strip()

The following results are obtained:

TCP    0.0.0.0:5001           0.0.0.0:0              LISTENING       2404

You can see that there is a TCP link listening to port 5001, and the last 2404 is the ID of this application.

2. End the application according to the application ID

_port = ().split(' ')[-1]
exec_cmd(f"taskkill /T /F /PID {_port}")  # Closed successfully

3. Run this script again according to the specified Python environment

(r"C:\Users\User4\Anaconda3\envs\my_env\ main_run.py",
                     cwd=r"C:\Users\User4\Desktop\my_python_bin")
("Restart the prediction model, delay of 20s...")

() is used here, which involves 2 directories and 1 file:

First line C:\Users\User4\Anaconda3\envs\my_env\: This is the full path of the interpreter that starts Python (preferably the full path)

The first line main_run.py: This is a python script file that needs to be restarted

Second line C:\Users\User4\Desktop\my_python_bin: This is the directory where the script is located

The above program can be understood as:

Interpreter: C:\Users\User4\Anaconda3\envs\my_env\

Script directory: C:\Users\User4\Desktop\my_python_bin\main_run.py

Complete example

import os
import subprocess
import time
from loguru import logger


def exec_cmd(cmd):
    """Execute commands and results"""
    r = (cmd)
    text = ()
    ()
    return text

def restart_my_python():
	cmd = "netstat -aon|findstr 5001"
	result = exec_cmd(cmd).strip()
	if result != "":
        (0.5)
        _port = ().split(' ')[-1]
        exec_cmd(f"taskkill /T /F /PID {_port}")  # Closed successfully	(r"C:\Users\User4\Anaconda3\envs\my_env\ main_run.py",
	                 cwd=r"C:\Users\User4\Desktop\my_python_bin")
	("Restart script, delayed by 5s...")
    (5)


restart_my_python()

Method supplement

1. Automatically restart the borted python script

For memory problems or other blabla problems (in short, it is not a code problem), the program may occasionally hang up, and we cannot keep an eye on the program all day long. What should we do? Write a script to check whether the program has hanged, and restart it if it has hanged. This is a good idea. The specific methods vary according to the operating system.

Method 1

In Linux, you can create a new script called:

#!/bin/sh
while [ 1 ]; do
python  --params
done

Start this in the command line:

sh 

Among them is the python script to be run, and –params are the parameters.

In Windows, you can create a bat file similarly. Since the bat is not very familiar, this part will be empty first.

Method 2

Add some extra code to check for exceptions in python, and if an exception occurs, it will be re-executeed. Here is a recursive method. In the following example, I set the maximum count to 3 in order to avoid infinite recursion.

import time
count = 0
def compute_number():
for i in xrange(10):
print 'count number: %s' % str(i+1)
(1)
raise Exception("a", "b")
def main():
print "AutoRes is starting"
print "Respawning"
global count
if count < 3:
try:
count += 1
compute_number()
except Exception, e:
print e
main()
finally:
print 'success'
if __name__ == "__main__":
main()

Method 3

Practices from here:

#!/usr/bin/env python

import os, sys, time

def main():

print "AutoRes is starting"

executable = 

args = [:]

(0, )

(1)

print "Respawning"

(executable, args)

if __name__ == "__main__":

main()

How to restart the script automatically

By using the try-except block in a Python script, exceptions that can cause the script to crash can be caught and scripts can be restarted after the exception is caught. The specific implementation is as follows:

import time
import os
import sys
def main():
    while True:
        try:
            # Main program logic            print("The script is running...")
            (10)  # Simulate long-running tasks        except Exception as e:
            print(f"An error occurred: {e}")
            print("The script will restart after 5 seconds...")
            (5)
            (, ['python'] + )
if __name__ == "__main__":
    main()

When an exception occurs, the script prints an error message and restarts itself after 5 seconds.

This is the end of this article about the detailed explanation of the method of restarting python scripts in Windows. For more related python scripts, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!