Skip to content

Instantly share code, notes, and snippets.

@YannBouyeron
Last active June 19, 2022 12:32
Show Gist options
  • Save YannBouyeron/1b9352d7d5aee543e5206f2db6042a4d to your computer and use it in GitHub Desktop.
Save YannBouyeron/1b9352d7d5aee543e5206f2db6042a4d to your computer and use it in GitHub Desktop.
Restart your script from himself
import os
import sys
import time
import subprocess
__file__ = os.path.abspath(sys.argv[0])
__dir__ = os.path.dirname(__file__)
os.chdir(os.path.expanduser("~"))
def restart():
time.sleep(5)
os.chdir(__dir__)
python_path = sys.executable
if sys.platform.startswith("win"):
python_path = python_path.replace("pythonw.exe", "python.exe")
pid = os.getpid()
cmd = 'taskkill /F /PID {2} && "{0}" "{1}"'.format(python_path, __file__, pid)
x = subprocess.check_output(cmd, shell=True)
#x = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT, stdin=subprocess.PIPE) # pour compiler avec pyinstaller
elif sys.platform.startswith("linux"):
os.execv(python_path, ["python3"] + [__file__])
# Or:
#pid = os.getpid()
#os.system("{0} {1} & kill {2}".format(python_path, __file__, pid))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment