44import subprocess
55import sys
66import textwrap
7+ import tempfile
78from pathlib import Path
89
910# Third-party
@@ -166,7 +167,7 @@ def get_update_command():
166167 return commands .get (method )
167168
168169
169- def check_for_update ():
170+ def check_for_update (relaunch : bool = False ):
170171 current_version = get_current_version ()
171172
172173 try :
@@ -189,7 +190,7 @@ def check_for_update():
189190 # Handle PYAPP separately
190191 if os .getenv ('PYAPP' ):
191192 if Confirm .ask ("Would you like to update now?" ):
192- return self_update ()
193+ return self_update (relaunch = relaunch )
193194 else :
194195 console .print ("[yellow]Update skipped. You can manually update later.[/yellow]" )
195196 return False
@@ -236,7 +237,7 @@ def pip_update_redfetch(update_command, latest_version):
236237 sys .exit (1 )
237238
238239
239- def self_update ():
240+ def self_update (relaunch : bool = False ):
240241 """Update with PYAPP."""
241242 try :
242243 console .print ("[bold]Performing self-update...[/bold]" )
@@ -249,11 +250,33 @@ def self_update():
249250 executable_path = get_executable_path ()
250251 update_command = [executable_path , 'self' , 'update' ]
251252
252- # Start the update process in a new console and exit the current one
253- subprocess .Popen (
254- update_command ,
255- creationflags = subprocess .CREATE_NEW_CONSOLE
256- )
253+ if relaunch and sys .platform == "win32" :
254+ update_cmdline = subprocess .list2cmdline (update_command )
255+ relaunch_cmdline = subprocess .list2cmdline ([executable_path ])
256+ batch_script = textwrap .dedent (f"""
257+ @echo off
258+ { update_cmdline }
259+ if %errorlevel% neq 0 (
260+ echo Update failed. Press any key to exit.
261+ pause > nul
262+ exit /b %errorlevel%
263+ )
264+ { relaunch_cmdline }
265+ (goto) 2>nul & del "%~f0"
266+ """ ).strip ()
267+ with tempfile .NamedTemporaryFile (
268+ mode = "w" ,
269+ delete = False ,
270+ suffix = ".bat" ,
271+ encoding = "utf-8"
272+ ) as batch_file :
273+ batch_file .write (batch_script )
274+
275+ subprocess .Popen (["cmd.exe" , "/c" , batch_file .name ])
276+ sys .exit (0 )
277+
278+ # Start the update process and exit the current one
279+ subprocess .Popen (update_command )
257280
258281 # Exit the current process to allow the update to proceed
259282 sys .exit (0 )
0 commit comments