Search code examples
pythonwxpython

Start Windows Batch file using python wxpython Button click Event


I want to start a windows batch file using python wxpython button click event.

import wx
import subprocess


class MyFrame(wx.Frame):
    """ Dervice new class of Frame"""
    def __init__ (self, parent, title)
        wx.Frame.__init__(self,parent,title=title,size=(410,355))
        panel = wx.Panel(self)           
        startbutton = wx.Button(panel, label="Start", pos=(200,70), size=(80,25))
        self.Bind(wx.EVT_BUTTON,self.StartClicked, startbutton)


    def StartClicked(self, event):
        print "Session started"
        self.filepath="C:\\cygwin64\\Sipp_3.2\\Auto.bat"
        subprocess.call(self.filepath)
        print "Session ended"


if __name__ == '__main__':
app = wx.App()
frame = MyFrame(None, "CallGenerator")
frame.Show()
app.MainLoop()

And below is output on each times, when i click the "Start" Button.

>Session started
>Session ended
>Session started
>Session ended

Code doesn't open the batch file. But when i execute the via command prompt,the batch file is executed through the command prompt.

I'm using pyscripter and How to open the batch file as a new window?

Similarly, if the batch file contains continous ping (ping ipaddress -t), the GUI becomes crashed.

Now what is the solution for my two problems.


Solution

  • The program probably is calling the batch file but because you do not redirect the process's stdout/stderr, you do not see what it is doing. You will probably want to use the subprocess module's communicate method to get the output from the batch file and update the GUI with that information.

    You mentioned that the batch file runs a long running process. This is going to block the GUI's mainloop, which is why the UI becomes unresponsive. If you used popen instead, you might be able to get around that, however the proper solution is to put the subprocess call inside a thread and then return the result from the thread to the UI via one of wx's thread-safe methods, such as wx.CallAfter or wx.PostEvent.

    See the following articles for more information: