Python,启动一个.py程序并终止前一个程序

2024-09-20 01:29:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从另一个python程序启动一个python程序,同时退出前一个程序。在

我所做的:

if(self.start_button.pression==1):
        os.system('python program_to_launch.py')
        sys.exit()

结果很明显,程序启动了“程序”_启动.py“等它完成运行。在

问题出在while循环中,在刚刚启动的程序中。 它的寿命是无限期的。在

问题是:上一个程序仍在等待新程序的结束,并且它不会执行系统出口()

我可以用'

注意事项:

method provided by this answer之后,我无法导入要启动的程序,因为我要终止第一个程序

^{pr2}$

所以我认为这不是一个解决办法。 以及命令exec file()

execfile('program_to_launch.py')

如链接答案所示,它提供了在程序执行过程中导入多个模块的问题_启动.py在


Tags: topyself程序ifossysexit
3条回答

假设我有以下文件(名为维护.py)如果要运行,请立即结束应用程序:

import wx

myApp = wx.App()
dial = wx.MessageDialog(None, f"This program is temporarily down for maintenance.\nWe will do our best to get it running again.\nThank you for your patience.", "Error", wx.OK|wx.ICON_ERROR)
dial.ShowModal()

使用子流程模块

这将是首选方法。用Popen命令调用它。在

^{pr2}$

有关详细信息,请参阅:https://docs.python.org/3.6/library/subprocess.html#popen-constructor

使用快捷方式

如果子进程对您不起作用,您可以创建一个快捷方式并使用os.startfile启动该快捷方式。例如,一个名为myShortcut.lnk的快捷方式对目标具有以下内容:C:\Windows\py.exe C:\Users\kblad\Desktop\maintenance.py将适用于以下代码:

import os
import sys
os.startfile("myShortcut")
sys.exit()

有关详细信息,请参阅:https://docs.python.org/3.6/library/os.html#os.startfile

我在寻找一种重新加载我自己的python脚本的方法,偶然看到了这篇文章:https://blog.petrzemek.net/2014/03/23/restarting-a-python-script-within-itself/

我不太明白['python']这个东西是从哪里来的,但是在阅读了操作系统执行*,我遇到了这个:

the first of these arguments is passed to the new program as its own name rather than as an argument a user may have typed on a command line. For the C programmer, this is the argv[0] passed to a program’s main(). For example, os.execv('/bin/echo', ['foo', 'bar']) will only print bar on standard output; foo will seem to be ignored.

https://docs.python.org/2/library/os.html 第15.1.5条

这可能对你有用,因为它似乎取代了原来的流程?在

我认为您可以在新线程或进程中启动程序:

from os import system
from threading import Thread
from sys import exit

if self.start_button.pression == 1:
    thread = Thread()
    thread.run = lambda: system('python program_to_launch.py')
    thread.start()

    exit()

相关问题 更多 >