本文整理汇总了Python中PyQt5.QtNetwork.QLocalServer.close方法的典型用法代码示例。如果您正苦于以下问题:Python QLocalServer.close方法的具体用法?Python QLocalServer.close怎么用?Python QLocalServer.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtNetwork.QLocalServer
的用法示例。
在下文中一共展示了QLocalServer.close方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Server
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import close [as 别名]
class Server(QObject):
dataReceived = pyqtSignal(list)
quit = pyqtSignal()
def __init__(self):
super().__init__()
self.conn = None
self.server = None
def create(self, name=piony.G_SOCKET_NAME):
QLocalServer.removeServer(name)
self.server = QLocalServer()
if not self.server.listen(name):
print("Error: server -- unable to start: {}."
.format(self.server.errorString()))
self.quit.emit()
self.server.newConnection.connect(self.notify)
def close(self):
self.server.close()
def notify(self):
logger.info("1 new conn")
# WARNING: when multiple connections, each will overwrite previous!
self.conn = self.server.nextPendingConnection()
self.conn.readyRead.connect(self.receiveData)
self.conn.disconnected.connect(self.conn.deleteLater)
def receiveData(self):
logger.info("waits for data")
ins = QDataStream(self.conn)
ins.setVersion(QDataStream.Qt_5_0)
if ins.atEnd():
return
argv = ins.readQVariant()
logger.info("reads '%s'", str(argv))
# Must be setted up on 'show' action. Move from beginning to appropriate.
action.search_dst_window()
self.dataReceived.emit(argv)
示例2: IPCServer
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import close [as 别名]
#.........这里部分代码省略.........
log.ipc.error("Ignoring invalid IPC data.")
self.got_invalid_data.emit()
self._socket.error.connect(self.on_error)
self._socket.disconnectFromServer()
@pyqtSlot()
def on_ready_read(self):
"""Read json data from the client."""
if self._socket is None:
# This happens when doing a connection while another one is already
# active for some reason.
log.ipc.warning("In on_ready_read with None socket!")
return
self._timer.start()
while self._socket is not None and self._socket.canReadLine():
data = bytes(self._socket.readLine())
self.got_raw.emit(data)
log.ipc.debug("Read from socket: {}".format(data))
try:
decoded = data.decode("utf-8")
except UnicodeDecodeError:
log.ipc.error("invalid utf-8: {}".format(binascii.hexlify(data)))
self._handle_invalid_data()
return
log.ipc.debug("Processing: {}".format(decoded))
try:
json_data = json.loads(decoded)
except ValueError:
log.ipc.error("invalid json: {}".format(decoded.strip()))
self._handle_invalid_data()
return
for name in ("args", "target_arg"):
if name not in json_data:
log.ipc.error("Missing {}: {}".format(name, decoded.strip()))
self._handle_invalid_data()
return
try:
protocol_version = int(json_data["protocol_version"])
except (KeyError, ValueError):
log.ipc.error("invalid version: {}".format(decoded.strip()))
self._handle_invalid_data()
return
if protocol_version != PROTOCOL_VERSION:
log.ipc.error("incompatible version: expected {}, " "got {}".format(PROTOCOL_VERSION, protocol_version))
self._handle_invalid_data()
return
cwd = json_data.get("cwd", None)
self.got_args.emit(json_data["args"], json_data["target_arg"], cwd)
@pyqtSlot()
def on_timeout(self):
"""Cancel the current connection if it was idle for too long."""
log.ipc.error("IPC connection timed out.")
self._socket.disconnectFromServer()
if self._socket is not None: # pragma: no cover
# on_socket_disconnected sets it to None
self._socket.waitForDisconnected(CONNECT_TIMEOUT)
if self._socket is not None: # pragma: no cover
# on_socket_disconnected sets it to None
self._socket.abort()
@pyqtSlot()
def update_atime(self):
"""Update the atime of the socket file all few hours.
From the XDG basedir spec:
To ensure that your files are not removed, they should have their
access time timestamp modified at least once every 6 hours of monotonic
time or the 'sticky' bit should be set on the file.
"""
path = self._server.fullServerName()
if not path:
log.ipc.error("In update_atime with no server path!")
return
log.ipc.debug("Touching {}".format(path))
os.utime(path)
def shutdown(self):
"""Shut down the IPC server cleanly."""
log.ipc.debug("Shutting down IPC")
if self._socket is not None:
self._socket.deleteLater()
self._socket = None
self._timer.stop()
if self._atime_timer is not None: # pragma: no branch
self._atime_timer.stop()
try:
self._atime_timer.timeout.disconnect(self.update_atime)
except TypeError:
pass
self._server.close()
self._server.deleteLater()
self._remove_server()
示例3: QtSingleApplication
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import close [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()
#.........这里部分代码省略.........
示例4: qlocalserver
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import close [as 别名]
def qlocalserver(qapp):
server = QLocalServer()
yield server
server.close()
server.deleteLater()
示例5: IDE
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import close [as 别名]
#.........这里部分代码省略.........
ns_Hide_misc = pyqtSignal(str)# dato: 'F4'
ns_Highlight_Word = pyqtSignal(str)# dato: 'Ctrl+Down'
ns_Import = pyqtSignal(str)# dato: 'Ctrl+I'
ns_Indent_less = pyqtSignal(str)# dato: 'Shift+Tab'
ns_Indent_more = pyqtSignal(str)# dato: 'Tab'
ns_Add_Bookmark_or_Breakpoint = pyqtSignal(str)# dato: 'Ctrl+B'
ns_Title_comment = pyqtSignal(str)# dato: ''
ns_Horizontal_line = pyqtSignal(str)# dato: ''
ns_Move_down = pyqtSignal(str)# dato: 'Alt+Down'
ns_Move_up = pyqtSignal(str)# dato: 'Alt+Up'
ns_Move_Tab_to_left = pyqtSignal(str)# dato: 'Ctrl+Shift+9'
ns_Move_Tab_to_right = pyqtSignal(str)# dato: 'Ctrl+Shift+0'
ns_Navigate_back = pyqtSignal(str)# dato: 'Alt+Left'
ns_Navigate_forward = pyqtSignal(str)# dato: 'Alt+Right'
ns_Open_file = pyqtSignal(str)# dato: 'Ctrl+O'
ns_Open_project = pyqtSignal(str)# dato: 'Ctrl+Shift+O'
ns_Open_recent_closed = pyqtSignal(str)# dato: 'Ctrl+Shift+T'
ns_paste = pyqtSignal(str)# dato: 'Ctrl+V'
ns_History_Paste = pyqtSignal(str)# dato: 'Ctrl+Alt+V'
ns_Print_file = pyqtSignal(str)# dato: 'Ctrl+P'
ns_Redo = pyqtSignal(str)# dato: 'Ctrl+Y'
ns_Reload_file = pyqtSignal(str)# dato: 'F5'
ns_Remove_line = pyqtSignal(str)# dato: 'Ctrl+E'
ns_Save_file = pyqtSignal(str)# dato: 'Ctrl+S'
ns_Save_project = pyqtSignal(str)# dato: 'Ctrl+Shift+S'
ns_Code_locator = pyqtSignal(str)# dato: 'Ctrl+K'
ns_Show_Paste_History = pyqtSignal(str)# dato: 'Ctrl+4'
ns_File_Opener = pyqtSignal(str)# dato: 'Ctrl+Alt+O'
ns_Help = pyqtSignal(str)# dato: 'F1'
ns_Show_Selector = pyqtSignal(str)# dato: 'Ctrl+`'
ns_Split_assistance = pyqtSignal(str)# dato: 'F10'
ns_change_tab_visibility = pyqtSignal(str)# dato: 'Shift+F1'
ns_Split_horizontal = pyqtSignal(str)# dato: 'F9'
示例6: IPCServer
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import close [as 别名]
#.........这里部分代码省略.........
@pyqtSlot(int)
def on_error(self, error):
"""Convenience method which calls _socket_error on an error."""
self._timer.stop()
log.ipc.debug("Socket error {}: {}".format(
self._socket.error(), self._socket.errorString()))
if error != QLocalSocket.PeerClosedError:
_socket_error("handling IPC connection", self._socket)
@pyqtSlot()
def handle_connection(self):
"""Handle a new connection to the server."""
if self.ignored:
return
if self._socket is not None:
log.ipc.debug("Got new connection but ignoring it because we're "
"still handling another one.")
return
socket = self._server.nextPendingConnection()
if socket is None:
log.ipc.debug("No new connection to handle.")
return
log.ipc.debug("Client connected.")
self._timer.start()
self._socket = socket
socket.readyRead.connect(self.on_ready_read)
if socket.canReadLine():
log.ipc.debug("We can read a line immediately.")
self.on_ready_read()
socket.error.connect(self.on_error)
if socket.error() not in (QLocalSocket.UnknownSocketError,
QLocalSocket.PeerClosedError):
log.ipc.debug("We got an error immediately.")
self.on_error(socket.error())
socket.disconnected.connect(self.on_disconnected)
if socket.state() == QLocalSocket.UnconnectedState:
log.ipc.debug("Socket was disconnected immediately.")
self.on_disconnected()
@pyqtSlot()
def on_disconnected(self):
"""Clean up socket when the client disconnected."""
log.ipc.debug("Client disconnected.")
self._timer.stop()
self._socket.deleteLater()
self._socket = None
# Maybe another connection is waiting.
self.handle_connection()
@pyqtSlot()
def on_ready_read(self):
"""Read json data from the client."""
if self._socket is None:
# this happened once and I don't know why
log.ipc.warn("In on_ready_read with None socket!")
return
self._timer.start()
while self._socket is not None and self._socket.canReadLine():
data = bytes(self._socket.readLine())
log.ipc.debug("Read from socket: {}".format(data))
try:
decoded = data.decode('utf-8')
except UnicodeDecodeError:
log.ipc.error("Ignoring invalid IPC data.")
log.ipc.debug("invalid data: {}".format(
binascii.hexlify(data)))
return
log.ipc.debug("Processing: {}".format(decoded))
try:
json_data = json.loads(decoded)
except ValueError:
log.ipc.error("Ignoring invalid IPC data.")
log.ipc.debug("invalid json: {}".format(decoded.strip()))
return
try:
args = json_data['args']
except KeyError:
log.ipc.error("Ignoring invalid IPC data.")
log.ipc.debug("no args: {}".format(decoded.strip()))
return
cwd = json_data.get('cwd', None)
app = objreg.get('app')
app.process_pos_args(args, via_ipc=True, cwd=cwd)
@pyqtSlot()
def on_timeout(self):
"""Cancel the current connection if it was idle for too long."""
log.ipc.error("IPC connection timed out.")
self._socket.close()
def shutdown(self):
"""Shut down the IPC server cleanly."""
if self._socket is not None:
self._socket.deleteLater()
self._socket = None
self._timer.stop()
self._server.close()
self._server.deleteLater()
self._remove_server()
示例7: _s_IDE
# 需要导入模块: from PyQt5.QtNetwork import QLocalServer [as 别名]
# 或者: from PyQt5.QtNetwork.QLocalServer import close [as 别名]
#.........这里部分代码省略.........
self._menuAbout = menu_about.MenuAbout(about)
self.load_toolbar()
#Plugin Manager
services = {
'editor': plugin_services.MainService(),
'toolbar': plugin_services.ToolbarService(self.toolbar),
'menuApp': plugin_services.MenuAppService(self.pluginsMenu),
'explorer': plugin_services.ExplorerService(),
'misc': plugin_services.MiscContainerService(self.misc)}
serviceLocator = plugin_manager.ServiceLocator(services)
self.plugin_manager = plugin_manager.PluginManager(resources.PLUGINS,
serviceLocator)
self.plugin_manager.discover()
#load all plugins!
self.plugin_manager.load_all()
#Tray Icon
self.trayIcon = updates.TrayIconUpdates(self)
self.trayIcon.show()
self._menuFile.openFile[str].connect(self.mainContainer.open_file)
self.mainContainer.fileSaved[str].connect(self.show_status_message)
self.mainContainer.recentTabsModified[list].connect(self._menuFile.update_recent_files)#'QStringList'
self.mainContainer.currentTabChanged[str].connect(self.actions.update_migration_tips)
self.mainContainer.updateFileMetadata.connect(self.actions.update_migration_tips)
self.mainContainer.migrationAnalyzed.connect(self.actions.update_migration_tips)
def _process_connection(self):
connection = self.s_listener.nextPendingConnection()
connection.waitForReadyRead()
data = connection.readAll()
connection.close()
if data:
files, projects = str(data).split(ipc.project_delimiter, 1)
files = [(x.split(':')[0], int(x.split(':')[1]))
for x in files.split(ipc.file_delimiter)]
projects = projects.split(ipc.project_delimiter)
self.load_session_files_projects(files, [], projects, None)
def load_toolbar(self):
self.toolbar.clear()
toolbar_items = {}
toolbar_items.update(self._menuFile.toolbar_items)
toolbar_items.update(self._menuView.toolbar_items)
toolbar_items.update(self._menuEdit.toolbar_items)
toolbar_items.update(self._menuSource.toolbar_items)
toolbar_items.update(self._menuProject.toolbar_items)
for item in settings.TOOLBAR_ITEMS:
if item == 'separator':
self.toolbar.addSeparator()
else:
tool_item = toolbar_items.get(item, None)
if tool_item is not None:
self.toolbar.addAction(tool_item)
#load action added by plugins, This is a special case when reload
#the toolbar after save the preferences widget
for toolbar_action in settings.get_toolbar_item_for_plugins():
self.toolbar.addAction(toolbar_action)
def load_external_plugins(self, paths):
for path in paths:
self.plugin_manager.add_plugin_dir(path)
#load all plugins!