Somputer
Somputer

Reputation: 1283

how can i stop module in python?

I have a simple code.

  1. start button press -> infinite loop and application clear
  2. stop button press -> infinite loop is stop by control c event

but I want to stop test2.py using other way not control c event.

because I made .exe file using pyinstaller by no console.

so control c event is not working...

how can I stop test2 module?

test.py :

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import test2
from PyQt4 import QtGui, QtCore
from win32api import GenerateConsoleCtrlEvent
from win32con import CTRL_C_EVENT


class Example(QtGui.QMainWindow):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):      

        btn1 = QtGui.QPushButton("Start", self)
        btn1.move(30, 50)

        btn2 = QtGui.QPushButton("Stop", self)
        btn2.move(150, 50)

        btn1.clicked.connect(self.start)            
        btn2.clicked.connect(self.stop)

        self.statusBar()

        self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle('Event sender')
        self.show()

    def start(self):
        sender = self.sender()
        self.statusBar().showMessage(sender.text())
        test2.main(app)

    def stop(self):
        sender = self.sender()
        self.statusBar().showMessage(sender.text())
        GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0)

def main():
    global app
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

test2.py :

def main(app):
    while 1:
        print "infinite loop"
        app.processEvents()

Upvotes: 0

Views: 669

Answers (2)

ekhumoro
ekhumoro

Reputation: 120798

Use a simple flag:

test2.py:

active = False

def main(app):
    global active
    active = True
    while active:
        print "infinite loop"
        app.processEvents()

test1.py:

class Example(QtGui.QMainWindow):
    ...

    def stop(self):
        ...
        test2.active = False

Upvotes: 1

abcd
abcd

Reputation: 10791

Raise any exception. If your goal is to mimic Ctrl-C, use KeyboardInterrupt. That is, replace the line

GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0)

with

raise KeyboardInterrupt('You pressed the stop button.')

in test.py.

Upvotes: 0

Related Questions