本文整理汇总了Python中PyQt5.QtNetwork.QLocalSocket类的典型用法代码示例。如果您正苦于以下问题:Python QLocalSocket类的具体用法?Python QLocalSocket怎么用?Python QLocalSocket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QLocalSocket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __readCommands
def __readCommands(self, connection: QLocalSocket) -> None:
line = connection.readLine()
while len(line) != 0: # There is also a .canReadLine()
try:
payload = json.loads(str(line, encoding = "ascii").strip())
command = payload["command"]
# Command: Remove all models from the build plate.
if command == "clear-all":
self._application.callLater(lambda: self._application.deleteAll())
# Command: Load a model file
elif command == "open":
self._application.callLater(lambda f = payload["filePath"]: self._application._openFile(f))
# Command: Activate the window and bring it to the top.
elif command == "focus":
# Operating systems these days prevent windows from moving around by themselves.
# 'alert' or flashing the icon in the taskbar is the best thing we do now.
main_window = self._application.getMainWindow()
if main_window is not None:
self._application.callLater(lambda: main_window.alert(0)) # type: ignore # I don't know why MyPy complains here
# Command: Close the socket connection. We're done.
elif command == "close-connection":
connection.close()
else:
Logger.log("w", "Received an unrecognized command " + str(command))
except json.decoder.JSONDecodeError as ex:
Logger.log("w", "Unable to parse JSON command '%s': %s", line, repr(ex))
line = connection.readLine()
示例2: get
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)
示例3: is_running
def is_running():
local_socket = QLocalSocket()
local_socket.connectToServer("ninja_ide")
if local_socket.state():
# It's running
result = (True, local_socket)
else:
# It's not running
result = (False, local_socket)
return result
示例4: test_other_error
def test_other_error(self, ipc_server, monkeypatch):
socket = QLocalSocket()
ipc_server._socket = socket
monkeypatch.setattr(socket, 'error',
lambda: QLocalSocket.ConnectionRefusedError)
monkeypatch.setattr(socket, 'errorString',
lambda: "Connection refused")
socket.setErrorString("Connection refused.")
with pytest.raises(ipc.Error, match=r"Error while handling IPC "
r"connection: Connection refused \(error 0\)"):
ipc_server.on_error(QLocalSocket.ConnectionRefusedError)
示例5: test_other_error
def test_other_error(self, ipc_server, monkeypatch):
socket = QLocalSocket()
ipc_server._socket = socket
monkeypatch.setattr(socket, 'error',
lambda: QLocalSocket.ConnectionRefusedError)
monkeypatch.setattr(socket, 'errorString',
lambda: "Connection refused")
socket.setErrorString("Connection refused.")
with pytest.raises(ipc.Error) as excinfo:
ipc_server.on_error(QLocalSocket.ConnectionRefusedError)
expected = ("Error while handling IPC connection: Connection refused "
"(error 0)")
assert str(excinfo.value) == expected
示例6: __init__
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)
示例7: init
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
示例8: connectToRunning
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'
示例9: __init__
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')
示例10: connect
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
示例11: __init__
def __init__(self, parent=None):
super(Client, self).__init__(parent)
self.blockSize = 0
self.currentFortune = None
hostLabel = QLabel("&Server name:")
self.hostLineEdit = QLineEdit("fortune")
hostLabel.setBuddy(self.hostLineEdit)
self.statusLabel = QLabel(
"This examples requires that you run the Fortune Server "
"example as well.")
self.statusLabel.setWordWrap(True)
self.getFortuneButton = QPushButton("Get Fortune")
self.getFortuneButton.setDefault(True)
quitButton = QPushButton("Quit")
buttonBox = QDialogButtonBox()
buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole)
buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole)
self.socket = QLocalSocket()
self.hostLineEdit.textChanged.connect(self.enableGetFortuneButton)
self.getFortuneButton.clicked.connect(self.requestNewFortune)
quitButton.clicked.connect(self.close)
self.socket.readyRead.connect(self.readFortune)
self.socket.error.connect(self.displayError)
mainLayout = QGridLayout()
mainLayout.addWidget(hostLabel, 0, 0)
mainLayout.addWidget(self.hostLineEdit, 0, 1)
mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2)
mainLayout.addWidget(buttonBox, 3, 0, 1, 2)
self.setLayout(mainLayout)
self.setWindowTitle("Fortune Client")
self.hostLineEdit.setFocus()
示例12: __init__
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)
示例13: send_to_running_instance
def send_to_running_instance(socketname, command, target_arg, *, 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.
Return:
True if connecting was successful, False if no connection was made.
"""
if socket is None:
socket = QLocalSocket()
log.ipc.debug("Connecting to {}".format(socketname))
socket.connectToServer(socketname)
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: {!r}".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
示例14: qlocalsocket
def qlocalsocket(qapp):
socket = QLocalSocket()
yield socket
socket.disconnectFromServer()
if socket.state() != QLocalSocket.UnconnectedState:
socket.waitForDisconnected(1000)
示例15: send_to_running_instance
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