gpt4 book ai didi

Windows 上的 Python 2.6 : how to terminate subprocess. Popen 带有 "shell=True"参数?

转载 作者:太空狗 更新时间:2023-10-29 21:25:18 25 4
gpt4 key购买 nike

有没有一种方法可以终止使用 subprocess.Popen 类启动且“shell”参数设置为“True”的进程?在下面的最小工作示例(使用 wxPython)中,您可以愉快地打开和终止记事本进程,但是如果您将 Popen“shell”参数更改为“True”,则记事本进程不会终止。

import wx
import threading
import subprocess

class MainWindow(wx.Frame):

def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title)
self.main_panel = wx.Panel(self, -1)

self.border_sizer = wx.BoxSizer()

self.process_button = wx.Button(self.main_panel, -1, "Start process", (50, 50))
self.process_button.Bind(wx.EVT_BUTTON, self.processButtonClick)

self.border_sizer.Add(self.process_button)
self.main_panel.SetSizerAndFit(self.border_sizer)
self.Fit()

self.Centre()
self.Show(True)

def processButtonClick(self, event):
if self.process_button.GetLabel() == "Start process":
self.process_button.SetLabel("End process")
self.notepad = threading.Thread(target = self.runProcess)
self.notepad.start()
else:
self.cancel = 1
self.process_button.SetLabel("Start process")

def runProcess(self):
self.cancel = 0

notepad_process = subprocess.Popen("notepad", shell = False)

while notepad_process.poll() == None: # While process has not yet terminated.
if self.cancel:
notepad_process.terminate()
break

def main():
app = wx.PySimpleApp()
mainView = MainWindow(None, wx.ID_ANY, "test")
app.MainLoop()

if __name__ == "__main__":
main()

为了这个问题,请接受“shell”确实必须等于“True”。

最佳答案

为什么要使用 shell=True

只是不要这样做。您不需要它,它会调用 shell,那是没用的。

我不接受它必须为 True,因为事实并非如此。使用 shell=True 只会给您带来问题而没有任何好处。不惜一切代价避免它。除非您正在运行一些 shell 内部命令,否则您不需要它,永远

关于Windows 上的 Python 2.6 : how to terminate subprocess. Popen 带有 "shell=True"参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/696345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com