Python script to call a second, independent instance of itself and then close old instance - Windows (script timeout self reset)

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To create a Python script that calls a second, independent instance of itself and then closes the old instance on Windows, you can use the subprocess module to start a new process and the sys module to close the old process.

Here's an example:

python
import subprocess
import sys

# Check if this is the initial instance of the script
if "new_instance" not in sys.argv:
# Start a new instance of the script
subprocess.Popen([sys.executable, __file__, "new_instance"])

# Close the old instance
sys.exit()

# Code for the new instance of the script goes here
print("New instance started")

In this example, we first check if the script is running in a new instance or the initial instance by checking if the string "new_instance" is in the command-line arguments (sys.argv). If it's not in the arguments, we start a new instance of the script using subprocess.Popen, passing in the sys.executable path and the path of the script file, as well as the "new_instance" argument. We then exit the old instance using sys.exit(), which will terminate the process.

In the new instance of the script, we can put the code that we want to run in the new process. In this example, we simply print a message to the console to indicate that the new instance has started.

Note that if the script takes a long time to run, it may time out and reset before the new instance is launched. In this case, you may need to adjust the script timeout settings in the Windows registry or use a different approach, such as a scheduled task or a service.