当前位置: 首页>>代码示例>>Python>>正文


Python QLocalSocket.waitForConnected方法代码示例

本文整理汇总了Python中PyQt5.QtNetwork.QLocalSocket.waitForConnected方法的典型用法代码示例。如果您正苦于以下问题:Python QLocalSocket.waitForConnected方法的具体用法?Python QLocalSocket.waitForConnected怎么用?Python QLocalSocket.waitForConnected使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt5.QtNetwork.QLocalSocket的用法示例。


在下文中一共展示了QLocalSocket.waitForConnected方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: send_to_running_instance

# 需要导入模块: from PyQt5.QtNetwork import QLocalSocket [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalSocket import waitForConnected [as 别名]
def send_to_running_instance(socketname, command, target_arg, *,
                             legacy_name=None, socket=None):
    """Try to send a commandline to a running instance.

    Blocks for CONNECT_TIMEOUT ms.

    Args:
        socketname: The name which should be used for the socket.
        command: The command to send to the running instance.
        target_arg: --target command line argument
        socket: The socket to read data from, or None.
        legacy_name: The legacy name to first try to connect to.

    Return:
        True if connecting was successful, False if no connection was made.
    """
    if socket is None:
        socket = QLocalSocket()

    if (legacy_name is not None and
            _has_legacy_server(legacy_name)):
        name_to_use = legacy_name
    else:
        name_to_use = socketname

    log.ipc.debug("Connecting to {}".format(name_to_use))
    socket.connectToServer(name_to_use)

    connected = socket.waitForConnected(CONNECT_TIMEOUT)
    if connected:
        log.ipc.info("Opening in existing instance")
        json_data = {'args': command, 'target_arg': target_arg,
                     'version': qutebrowser.__version__,
                     'protocol_version': PROTOCOL_VERSION}
        try:
            cwd = os.getcwd()
        except OSError:
            pass
        else:
            json_data['cwd'] = cwd
        line = json.dumps(json_data) + '\n'
        data = line.encode('utf-8')
        log.ipc.debug("Writing: {}".format(data))
        socket.writeData(data)
        socket.waitForBytesWritten(WRITE_TIMEOUT)
        if socket.error() != QLocalSocket.UnknownSocketError:
            raise SocketError("writing to running instance", socket)
        else:
            socket.disconnectFromServer()
            if socket.state() != QLocalSocket.UnconnectedState:
                socket.waitForDisconnected(CONNECT_TIMEOUT)
            return True
    else:
        if socket.error() not in (QLocalSocket.ConnectionRefusedError,
                                  QLocalSocket.ServerNotFoundError):
            raise SocketError("connecting to running instance", socket)
        else:
            log.ipc.debug("No existing instance present (error {})".format(
                socket.error()))
            return False
开发者ID:NicoloPernigo,项目名称:qutebrowser,代码行数:62,代码来源:ipc.py

示例2: init

# 需要导入模块: from PyQt5.QtNetwork import QLocalSocket [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalSocket import waitForConnected [as 别名]
def init():
    """Start listening to incoming connections."""
    global _server
    if _server is not None:
        return
    
    server = QLocalServer(None)
    
    # find a free socket name to use
    for name in ids():
        if server.listen(name):
            break
    else:
        # all names failed, try to contact and remove stale file if that fails
        socket = QLocalSocket()
        for name in ids():
            socket.connectToServer(name)
            if not socket.waitForConnected(10000):
                QLocalServer.removeServer(name)
                if server.listen(name):
                    break
            else:
                socket.disconnectFromServer()
        else:
            # no ids left, don't listen
            return
    app.aboutToQuit.connect(server.close)
    server.newConnection.connect(slot_new_connection)
    os.environ["FRESCOBALDI_SOCKET"] = name
    _server = server
开发者ID:AlexSchr,项目名称:frescobaldi,代码行数:32,代码来源:__init__.py

示例3: send_to_running_instance

# 需要导入模块: from PyQt5.QtNetwork import QLocalSocket [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalSocket import waitForConnected [as 别名]
def send_to_running_instance(cmdlist):
    """Try to send a commandline to a running instance.

    Blocks for CONNECT_TIMEOUT ms.

    Args:
        cmdlist: A list to send (URLs/commands)

    Return:
        True if connecting was successful, False if no connection was made.
    """
    socket = QLocalSocket()
    socket.connectToServer(SOCKETNAME)
    connected = socket.waitForConnected(100)
    if connected:
        log.ipc.info("Opening in existing instance")
        line = json.dumps(cmdlist) + '\n'
        data = line.encode('utf-8')
        log.ipc.debug("Writing: {}".format(data))
        socket.writeData(data)
        socket.waitForBytesWritten(WRITE_TIMEOUT)
        if socket.error() != QLocalSocket.UnknownSocketError:
            _socket_error("writing to running instance", socket)
        else:
            return True
    else:
        if socket.error() not in (QLocalSocket.ConnectionRefusedError,
                                  QLocalSocket.ServerNotFoundError):
            _socket_error("connecting to running instance", socket)
        else:
            log.ipc.debug("No existing instance present (error {})".format(
                socket.error()))
            return False
开发者ID:anweshknayak,项目名称:qutebrowser,代码行数:35,代码来源:ipc.py

示例4: _send_to_running_instance

# 需要导入模块: from PyQt5.QtNetwork import QLocalSocket [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalSocket import waitForConnected [as 别名]
    def _send_to_running_instance(self, payload: bytes, pid: int) -> None:
        from PyQt5.QtCore import QByteArray
        from PyQt5.QtNetwork import QLocalSocket

        named_pipe = f"{BUNDLE_IDENTIFIER}.protocol.{pid}"
        log.debug(
            f"Opening a local socket to the running instance on {named_pipe} "
            f"(payload={self.redact_payload(payload)})"
        )
        client = QLocalSocket()
        try:
            client.connectToServer(named_pipe)

            if not client.waitForConnected():
                log.error(f"Unable to open client socket: {client.errorString()}")
                return

            client.write(QByteArray(payload))
            client.waitForBytesWritten()
            client.disconnectFromServer()
            if client.state() == QLocalSocket.ConnectedState:
                client.waitForDisconnected()
        finally:
            del client
        log.debug("Successfully closed client socket")
开发者ID:nuxeo,项目名称:nuxeo-drive,代码行数:27,代码来源:commandline.py

示例5: get

# 需要导入模块: from PyQt5.QtNetwork import QLocalSocket [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalSocket import waitForConnected [as 别名]
def get():
    """Return a remote Frescobaldi, or None if not available."""
    socket = QLocalSocket()
    name = os.environ.get("FRESCOBALDI_SOCKET")
    for name in (name,) if name else ids():
        socket.connectToServer(name)
        if socket.waitForConnected(5000):
            from . import api
            return api.Remote(socket)
开发者ID:AlexSchr,项目名称:frescobaldi,代码行数:11,代码来源:__init__.py

示例6: startClient

# 需要导入模块: from PyQt5.QtNetwork import QLocalSocket [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalSocket import waitForConnected [as 别名]
    def startClient(self) -> bool:
        Logger.log("i", "Checking for the presence of an ready running Cura instance.")
        single_instance_socket = QLocalSocket(self._application)
        Logger.log("d", "Full single instance server name: %s", single_instance_socket.fullServerName())
        single_instance_socket.connectToServer("ultimaker-cura")
        single_instance_socket.waitForConnected(msecs = 3000)  # wait for 3 seconds

        if single_instance_socket.state() != QLocalSocket.ConnectedState:
            return False

        # We only send the files that need to be opened.
        if not self._files_to_open:
            Logger.log("i", "No file need to be opened, do nothing.")
            return True

        if single_instance_socket.state() == QLocalSocket.ConnectedState:
            Logger.log("i", "Connection has been made to the single-instance Cura socket.")

            # Protocol is one line of JSON terminated with a carriage return.
            # "command" field is required and holds the name of the command to execute.
            # Other fields depend on the command.

            payload = {"command": "clear-all"}
            single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding = "ascii"))

            payload = {"command": "focus"}
            single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding = "ascii"))

            for filename in self._files_to_open:
                payload = {"command": "open", "filePath": os.path.abspath(filename)}
                single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding = "ascii"))

            payload = {"command": "close-connection"}
            single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding = "ascii"))

            single_instance_socket.flush()
            single_instance_socket.waitForDisconnected()
        return True
开发者ID:TinkerGnome,项目名称:Cura,代码行数:40,代码来源:SingleInstance.py

示例7: send_to_running_instance

# 需要导入模块: from PyQt5.QtNetwork import QLocalSocket [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalSocket import waitForConnected [as 别名]
def send_to_running_instance(socketname, command):
    """Try to send a commandline to a running instance.

    Blocks for CONNECT_TIMEOUT ms.

    Args:
        socketname: The name which should be used for the socket.
        command: The command to send to the running instance.

    Return:
        True if connecting was successful, False if no connection was made.
    """
    socket = QLocalSocket()
    log.ipc.debug("Connecting to {}".format(socketname))
    socket.connectToServer(socketname)
    connected = socket.waitForConnected(100)
    if connected:
        log.ipc.info("Opening in existing instance")
        json_data = {'args': command}
        try:
            cwd = os.getcwd()
        except OSError:
            pass
        else:
            json_data['cwd'] = cwd
        line = json.dumps(json_data) + '\n'
        data = line.encode('utf-8')
        log.ipc.debug("Writing: {}".format(data))
        socket.writeData(data)
        socket.waitForBytesWritten(WRITE_TIMEOUT)
        if socket.error() != QLocalSocket.UnknownSocketError:
            _socket_error("writing to running instance", socket)
        else:
            socket.disconnectFromServer()
            if socket.state() != QLocalSocket.UnconnectedState:
                socket.waitForDisconnected(100)
            return True
    else:
        if socket.error() not in (QLocalSocket.ConnectionRefusedError,
                                  QLocalSocket.ServerNotFoundError):
            _socket_error("connecting to running instance", socket)
        else:
            log.ipc.debug("No existing instance present (error {})".format(
                socket.error()))
            return False
开发者ID:jnphilipp,项目名称:qutebrowser,代码行数:47,代码来源:ipc.py

示例8: QtSingleApplication

# 需要导入模块: from PyQt5.QtNetwork import QLocalSocket [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalSocket import waitForConnected [as 别名]
class QtSingleApplication(QApplication):
    """
    This class makes sure that we can only start one Tribler application.
    When a user tries to open a second Tribler instance, the current active one will be brought to front.
    """

    messageReceived = pyqtSignal(unicode)

    def __init__(self, win_id, *argv):

        logfunc = logging.info
        logfunc(sys._getframe().f_code.co_name + '()')

        QApplication.__init__(self, *argv)

        self._id = win_id
        self._activation_window = None
        self._activate_on_message = False

        # Is there another instance running?
        self._outSocket = QLocalSocket()
        self._outSocket.connectToServer(self._id)
        self._isRunning = self._outSocket.waitForConnected()

        self._outStream = None
        self._inSocket = None
        self._inStream = None
        self._server = None

        if self._isRunning:
            # Yes, there is.
            self._outStream = QTextStream(self._outSocket)
            self._outStream.setCodec('UTF-8')
        else:
            # No, there isn't, at least not properly.
            # Cleanup any past, crashed server.
            error = self._outSocket.error()
            logfunc(LOGVARSTR % ('self._outSocket.error()', error))
            if error == QLocalSocket.ConnectionRefusedError:
                logfunc('received QLocalSocket.ConnectionRefusedError; ' + \
                        'removing server.')
                self.close()
                QLocalServer.removeServer(self._id)
            self._outSocket = None
            self._server = QLocalServer()
            self._server.listen(self._id)
            self._server.newConnection.connect(self._on_new_connection)

        logfunc(sys._getframe().f_code.co_name + '(): returning')

    def close(self):
        logfunc = logging.info
        logfunc(sys._getframe().f_code.co_name + '()')
        if self._inSocket:
            self._inSocket.disconnectFromServer()
        if self._outSocket:
            self._outSocket.disconnectFromServer()
        if self._server:
            self._server.close()
        logfunc(sys._getframe().f_code.co_name + '(): returning')

    def is_running(self):
        return self._isRunning

    def get_id(self):
        return self._id

    def activation_window(self):
        return self._activation_window

    def set_activation_window(self, activation_window, activate_on_message=True):
        self._activation_window = activation_window
        self._activate_on_message = activate_on_message

    def activate_window(self):
        if not self._activation_window:
            return
        self._activation_window.setWindowState(
            self._activation_window.windowState() & ~Qt.WindowMinimized)
        self._activation_window.raise_()

    def send_message(self, msg):
        if not self._outStream:
            return False
        self._outStream << msg << '\n'
        self._outStream.flush()
        return self._outSocket.waitForBytesWritten()

    def _on_new_connection(self):
        if self._inSocket:
            self._inSocket.readyRead.disconnect(self._on_ready_read)
        self._inSocket = self._server.nextPendingConnection()
        if not self._inSocket:
            return
        self._inStream = QTextStream(self._inSocket)
        self._inStream.setCodec('UTF-8')
        self._inSocket.readyRead.connect(self._on_ready_read)
        if self._activate_on_message:
            self.activate_window()

#.........这里部分代码省略.........
开发者ID:synctext,项目名称:tribler,代码行数:103,代码来源:single_application.py

示例9: QtSingleApplication

# 需要导入模块: from PyQt5.QtNetwork import QLocalSocket [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalSocket import waitForConnected [as 别名]
class QtSingleApplication(QApplication):

    messageReceived = pyqtSignal(str)

    def __init__(self, id, *argv):

        super(QtSingleApplication, self).__init__(*argv)
        self._id = id
        self._activationWindow = None
        self._activateOnMessage = False

        # Is there another instance running?
        self._outSocket = QLocalSocket()
        self._outSocket.connectToServer(self._id)
        self._isRunning = self._outSocket.waitForConnected()

        if self._isRunning:
            # Yes, there is.
            self._outStream = QTextStream(self._outSocket)
            self._outStream.setCodec("UTF-8")
        else:
            # No, there isn't.
            self._outSocket = None
            self._outStream = None
            self._inSocket = None
            self._inStream = None
            self._server = QLocalServer()
            self._server.listen(self._id)
            self._server.newConnection.connect(self._onNewConnection)

    def isRunning(self):
        return self._isRunning

    def id(self):
        return self._id

    def activationWindow(self):
        return self._activationWindow

    def setActivationWindow(self, activationWindow, activateOnMessage=True):
        self._activationWindow = activationWindow
        self._activateOnMessage = activateOnMessage

    def activateWindow(self):
        if not self._activationWindow:
            return

        self._activationWindow.show()
        self._activationWindow.setWindowState(self._activationWindow.windowState() & ~Qt.WindowMinimized)
        self._activationWindow.raise_()
        self._activationWindow.activateWindow()

    def sendMessage(self, msg):
        if not self._outStream:
            return False
        self._outStream << msg << "\n"
        self._outStream.flush()
        return self._outSocket.waitForBytesWritten()

    def _onNewConnection(self):
        if self._inSocket:
            self._inSocket.readyRead.disconnect(self._onReadyRead)
        self._inSocket = self._server.nextPendingConnection()
        if not self._inSocket:
            return
        self._inStream = QTextStream(self._inSocket)
        self._inStream.setCodec("UTF-8")
        self._inSocket.readyRead.connect(self._onReadyRead)
        if self._activateOnMessage:
            self.activateWindow()

    def _onReadyRead(self):
        while True:
            msg = self._inStream.readLine()
            if not msg:
                break
            self.messageReceived.emit(msg)
开发者ID:narthollis,项目名称:eve-mcl,代码行数:79,代码来源:qtsingleapplication.py

示例10: SingleApplicationClient

# 需要导入模块: from PyQt5.QtNetwork import QLocalSocket [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalSocket import waitForConnected [as 别名]
class SingleApplicationClient(object):
    """
    Class implementing the single application client base class.
    """
    def __init__(self, name):
        """
        Constructor
        
        @param name name of the local server to connect to (string)
        """
        self.name = name
        self.connected = False
        
    def connect(self):
        """
        Public method to connect the single application client to its server.
        
        @return value indicating success or an error number. Value is one of:
            <table>
                <tr><td>0</td><td>No application is running</td></tr>
                <tr><td>1</td><td>Application is already running</td></tr>
            </table>
        """
        self.sock = QLocalSocket()
        self.sock.connectToServer(self.name)
        if self.sock.waitForConnected(10000):
            self.connected = True
            return 1
        else:
            err = self.sock.error()
            if err == QLocalSocket.ServerNotFoundError:
                return 0
            else:
                return -err
        
    def disconnect(self):
        """
        Public method to disconnect from the Single Appliocation server.
        """
        self.sock.disconnectFromServer()
        self.connected = False
    
    def processArgs(self, args):
        """
        Public method to process the command line args passed to the UI.
        
        <b>Note</b>: This method must be overridden by subclasses.
        
        @param args command line args (list of strings)
        @exception RuntimeError raised to indicate that this method must be
            implemented by a subclass
        """
        raise RuntimeError("'processArgs' must be overridden")
    
    def sendCommand(self, cmd):
        """
        Public method to send the command to the application server.
        
        @param cmd command to be sent (string)
        """
        if self.connected:
            self.sock.write(cmd)
            self.sock.flush()
        
    def errstr(self):
        """
        Public method to return a meaningful error string for the last error.
        
        @return error string for the last error (string)
        """
        return self.sock.errorString()
开发者ID:testmana2,项目名称:test,代码行数:73,代码来源:SingleApplication.py

示例11: MainForm

# 需要导入模块: from PyQt5.QtNetwork import QLocalSocket [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalSocket import waitForConnected [as 别名]

#.........这里部分代码省略.........
      
   def itemClicked(self):
      sender = self.sender()
      if sender.item.folder:
         self.setCurrentItem(sender.item)
         self.refresh(False)
      else:
         flags = ['f', 'F', 'u', 'U', 'd', 'D', 'n', 'N', 'i', 'k', 'v', 'm']
         command = sender.item.command
         for i in flags:
            command = command.replace('%' + i, '')
         # %c needs a proper value in some cases
         command = command.replace('%c', '"%s"' % sender.item.name)
         working = sender.item.working
         if not os.path.isdir(working):
            working = None
            
         # Need to redirect stdout and stderr so if the process writes something it won't fail
         with open(os.path.devnull, 'w') as devnull:
            Popen(command + '&', stdout=devnull, stderr=devnull, shell=True, cwd=working)
         self.hideOrClose()
         
         
   def backClicked(self):
      if self.currentItem:
         self.setCurrentItem(self.currentItem.parent)
         self.refresh(False)
         
         
   def setCurrentItem(self, item):
      self.currentItem = item
      if item != None:
         self.currentLabel.setText(item.name)
         if item.parent != None:
            self.backButton.setText(item.parent.name)
         else:
            self.backButton.setText('Favorites')
      else:
         self.currentLabel.setText('')
         self.backButton.setText('Favorites')
         
         
   def settingsClicked(self):
      form = SettingsForm(self)
      form.quitCheck.setChecked(self.settings['quit'])
      theme = self.settings.get('iconTheme')
      if theme:
         form.themeCombo.setCurrentIndex(form.themeCombo.findText(theme))
      
      self.holdOpen = True
      form.exec_()
      self.checkMouse()
      self.holdOpen = False
      
      if form.accepted:
         self.settings['quit'] = form.quitCheck.isChecked()
      
      
   def firstRun(self):
      QMessageBox.information(self, 'First Time?', 'Your menu is currently empty.  It is recommended that you import an existing menu file.')
      self.settingsClicked()
      
      
   def connectToRunning(self):
      self.socket = QLocalSocket()
      self.socket.connectToServer('nemuSocket')
      self.socket.waitForConnected(1000)
      
      if self.socket.state() == QLocalSocket.ConnectedState:
         print 'Server found'
         if self.socket.waitForReadyRead(3000):
            line = self.socket.readLine()
            print line
         else:
            print self.socket.errorString()
         sys.exit()
      else:
         print 'No server running'
      
      
   def handleConnection(self):
      import datetime
      print "Got connection", datetime.datetime.now()
      
      connection = self.server.nextPendingConnection()
      connection.write('connected')
      del connection
      
      self.setCurrentItem(None)
      self.filterBox.setText('')
      self.refresh(False)
      self.show()
      print "Showed", datetime.datetime.now()
      return
      
      
   # Call periodically to keep data resident in memory (hopefully)
   def keepalive(self):
      if self.isHidden():
         self.refresh(False)
开发者ID:cybertron,项目名称:nemu,代码行数:104,代码来源:MainForm.py

示例12: Eddy

# 需要导入模块: from PyQt5.QtNetwork import QLocalSocket [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalSocket import waitForConnected [as 别名]
class Eddy(QApplication):
    """
    This class implements the main Qt application.
    """
    messageReceived = pyqtSignal(str)

    def __init__(self, argv):
        """
        Initialize Eddy.
        :type argv: list
        """
        super().__init__(argv)

        parser = ArgumentParser()
        parser.add_argument('--nosplash', dest='nosplash', action='store_true')
        parser.add_argument('--tests', dest='tests', action='store_true')

        options, args = parser.parse_known_args(args=argv)

        self.inSocket = None
        self.inStream = None
        self.outSocket = QLocalSocket()
        self.outSocket.connectToServer(APPID)
        self.outStream = None
        self.isRunning = self.outSocket.waitForConnected()
        self.mainwindow = None
        self.pendingOpen = []
        self.server = None

        # We do not initialize a new instance of Eddy if there is a process running
        # and we are not executing the tests suite: we'll create a socket instead so we can
        # exchange messages between the 2 processes (this one and the already running one).
        if self.isRunning and not options.tests:
            self.outStream = QTextStream(self.outSocket)
            self.outStream.setCodec('UTF-8')
        else:
            self.server = QLocalServer()
            self.server.listen(APPID)
            self.outSocket = None
            self.outStream = None

            connect(self.server.newConnection, self.newConnection)
            connect(self.messageReceived, self.readMessage)

            ############################################################################################################
            #                                                                                                          #
            #   PERFORM EDDY INITIALIZATION                                                                            #
            #                                                                                                          #
            ############################################################################################################

            # Draw the splashscreen.
            self.splashscreen = None
            if not options.nosplash:
                self.splashscreen = SplashScreen(min_splash_time=4)
                self.splashscreen.show()

            # Setup layout.
            self.setStyle(Clean('Fusion'))
            with open(expandPath('@eddy/ui/clean.qss')) as sheet:
                self.setStyleSheet(sheet.read())

            # Create the main window.
            self.mainwindow = MainWindow()

            # Close the splashscreen.
            if self.splashscreen:
                self.splashscreen.wait(self.splashscreen.remaining)
                self.splashscreen.close()

            # Display the mainwindow.
            self.mainwindow.show()

            if Platform.identify() is Platform.Darwin:
                # On MacOS files being opened are handled as a QFileOpenEvent but since we don't
                # have a Main Window initialized we store them locally and we open them here.
                for filepath in self.pendingOpen:
                    self.openFile(filepath)
                self.pendingOpen = []
            else:
                # Perform document opening if files have been added to sys.argv. This is not
                # executed on Mac OS since this is already handled as a QFileOpenEvent instance.
                for filepath in argv:
                    self.openFile(filepath)

    ####################################################################################################################
    #                                                                                                                  #
    #   EVENTS                                                                                                         #
    #                                                                                                                  #
    ####################################################################################################################

    def event(self, event):
        """
        Executed when an event is received.
        :type event: T <= QEvent | QFileOpenEvent
        """
        if event.type() == QEvent.FileOpen:
            self.pendingOpen = [event.file()]
            return True
        return super().event(event)

#.........这里部分代码省略.........
开发者ID:gitter-badger,项目名称:eddy,代码行数:103,代码来源:application.py

示例13: SingleApplication

# 需要导入模块: from PyQt5.QtNetwork import QLocalSocket [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalSocket import waitForConnected [as 别名]
class SingleApplication(QtWidgets.QApplication):
    '''
    Inheriting from QApplication, executing main App instead.
    Watching whether the app is already running.
    If so, quit befor execution.
    '''
    messageReceived = QtCore.pyqtSignal(str)

    def __init__(self, id, *argv):

        super(SingleApplication, self).__init__(*argv)
        self._id = id
        self._activationWindow = None
        self._activateOnMessage = False

        # Check if another instance is running?
        self._outSocket = QLocalSocket()
        self._outSocket.connectToServer(self._id)
        self._isRunning = self._outSocket.waitForConnected()

        if self._isRunning:
            self._outStream = QtCore.QTextStream(self._outSocket)
            self._outStream.setCodec('UTF-8')
        else:
            self._outSocket = None
            self._outStream = None
            self._inSocket = None
            self._inStream = None
            self._server = QLocalServer()
            self._server.removeServer(self._id)  # if existing after crash-exit
            self._server.listen(self._id)
            self._server.newConnection.connect(self._onNewConnection)

    def isRunning(self):
        return self._isRunning

    def id(self):
        return self._id

    def activationWindow(self):
        return self._activationWindow

    def setActivationWindow(self, activationWindow, activateOnMessage=True):
        self._activationWindow = activationWindow
        self._activateOnMessage = activateOnMessage

    def activateWindow(self):
        if not self._activationWindow:
            return
        self._activationWindow.setWindowState(
            self._activationWindow.windowState() & ~QtCore.Qt.WindowMinimized)
        self._activationWindow.show()
        self._activationWindow.activateWindow()

    def sendMessage(self, msg):
        if not self._outStream:
            return False
        self._outStream << msg << '\n'
        self._outStream.flush()
        return self._outSocket.waitForBytesWritten()

    def _onNewConnection(self):
        if self._inSocket:
            self._inSocket.readyRead.disconnect(self._onReadyRead)
        self._inSocket = self._server.nextPendingConnection()
        if not self._inSocket:
            return
        self._inStream = QtCore.QTextStream(self._inSocket)
        self._inStream.setCodec('UTF-8')
        self._inSocket.readyRead.connect(self._onReadyRead)
        if self._activateOnMessage:
            self.activateWindow()

    def _onReadyRead(self):
        while True:
            msg = self._inStream.readLine()
            if not msg:
                break
            self.messageReceived.emit(msg)
开发者ID:qandak,项目名称:sumcalc,代码行数:81,代码来源:singleton.py


注:本文中的PyQt5.QtNetwork.QLocalSocket.waitForConnected方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。