本文整理汇总了Python中PyQt5.QtCore.QSocketNotifier类的典型用法代码示例。如果您正苦于以下问题:Python QSocketNotifier类的具体用法?Python QSocketNotifier怎么用?Python QSocketNotifier使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QSocketNotifier类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: FileListStream
class FileListStream(QObject):
"""FileListStream represents a stream of filenames read from stdin or
from other sources that is visualized in the FileView.
"""
sig_file_added = pyqtSignal(FileInfo)
sig_end_of_stream = pyqtSignal()
sig_error = pyqtSignal()
@staticmethod
def from_location(app, linesep, location):
if location.get_path() in ["/stdin", "stdin"]:
tee_fd, stream_id = app.stream_manager.get_stdin()
else:
raise Exception("FileListStream: unknown location: %s", location)
return FileListStream(app.vfs, tee_fd, linesep)
@property
def sig_finished(self):
return self.sig_end_of_stream
def __init__(self, vfs: 'VirtualFilesystem',
fp: IO, linesep: str = "\n") -> None:
super().__init__()
self.vfs = vfs
self.fp = fp
self.linesep = linesep
self.readliner = None
self.socket_notifier: Optional[QSocketNotifier] = None
def close(self):
self.fp.close()
def start(self):
self.readliner = non_blocking_readline(self.fp, self.linesep)
self.socket_notifier = QSocketNotifier(self.fp.fileno(), QSocketNotifier.Read)
self.socket_notifier.activated.connect(self._on_activated)
def _on_activated(self, fd: int) -> None:
while True:
try:
filename: str = next(self.readliner)
except StopIteration:
self.socket_notifier.setEnabled(False)
self.socket_notifier = None
self.sig_end_of_stream.emit()
return
else:
if filename is not None:
location = Location.from_path(filename)
self.sig_file_added.emit(self.vfs.get_fileinfo(location))
else:
return
示例2: __init__
def __init__(self, xmms):
QObject.__init__(self)
fd = xmms.get_fd()
self.xmms = xmms
self.xmms.set_need_out_fun(self.checkWrite)
self.rSock = QSocketNotifier(fd, QSocketNotifier.Read, self)
self.rSock.activated.connect(self.handleRead)
self.rSock.setEnabled(True)
self.wSock = QSocketNotifier(fd, QSocketNotifier.Write, self)
self.wSock.activated.connect(self.handleWrite)
self.wSock.setEnabled(False)
示例3: XMMSConnector
class XMMSConnector(QObject):
def __init__(self, xmms):
QObject.__init__(self)
fd = xmms.get_fd()
self.xmms = xmms
self.xmms.set_need_out_fun(self.checkWrite)
self.rSock = QSocketNotifier(fd, QSocketNotifier.Read, self)
self.rSock.activated.connect(self.handleRead)
self.rSock.setEnabled(True)
self.wSock = QSocketNotifier(fd, QSocketNotifier.Write, self)
self.wSock.activated.connect(self.handleWrite)
self.wSock.setEnabled(False)
def checkWrite(self, i):
if self.xmms.want_ioout():
self.toggleWrite(True)
else:
self.toggleWrite(False)
def toggleRead(self, bool_val):
self.rSock.setEnabled(bool_val)
def toggleWrite(self, bool_val):
self.wSock.setEnabled(bool_val)
def handleRead(self, i):
self.xmms.ioin()
def handleWrite(self, i):
self.xmms.ioout()
示例4: activate
def activate(self):
"""Set up signal handlers.
On Windows this uses a QTimer to periodically hand control over to
Python so it can handle signals.
On Unix, it uses a QSocketNotifier with os.set_wakeup_fd to get
notified.
"""
self._orig_handlers[signal.SIGINT] = signal.signal(
signal.SIGINT, self.interrupt)
self._orig_handlers[signal.SIGTERM] = signal.signal(
signal.SIGTERM, self.interrupt)
if os.name == 'posix' and hasattr(signal, 'set_wakeup_fd'):
# pylint: disable=import-error,no-member,useless-suppression
import fcntl
read_fd, write_fd = os.pipe()
for fd in [read_fd, write_fd]:
flags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
self._notifier = QSocketNotifier(read_fd, QSocketNotifier.Read,
self)
self._notifier.activated.connect(self.handle_signal_wakeup)
self._orig_wakeup_fd = signal.set_wakeup_fd(write_fd)
else:
self._timer.start(1000)
self._timer.timeout.connect(lambda: None)
self._activated = True
示例5: _setup_signals
def _setup_signals(self):
"""Set up signal handlers.
On Windows this uses a QTimer to periodically hand control over to
Python so it can handle signals.
On Unix, it uses a QSocketNotifier with os.set_wakeup_fd to get
notified.
"""
signal.signal(signal.SIGINT, self.interrupt)
signal.signal(signal.SIGTERM, self.interrupt)
if os.name == 'posix' and hasattr(signal, 'set_wakeup_fd'):
import fcntl
read_fd, write_fd = os.pipe()
for fd in (read_fd, write_fd):
flags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
self._signal_notifier = QSocketNotifier(
read_fd, QSocketNotifier.Read, self)
self._signal_notifier.activated.connect(self._handle_signal_wakeup)
signal.set_wakeup_fd(write_fd)
else:
self._signal_timer = usertypes.Timer(self, 'python_hacks')
self._signal_timer.start(1000)
self._signal_timer.timeout.connect(lambda: None)
示例6: register_io
def register_io(self, fd, callback, mode, *args, **kwargs):
handler = six.next(self._handlers)
notifier = QSocketNotifier(self.fd_number(fd), self.constants[mode])
with self._mutex:
self._io_handlers[handler] = notifier
def _io_cb(*_):
if not self._safe_callback(callback, fd, *args, **kwargs):
self.unregister_io(handler)
with self._mutex:
# we need to store the closure callback to avoid the garbage collector
# from collecting the closure
self._io_handlers[handler] = (notifier, _io_cb)
notifier.setEnabled(True)
notifier.activated.connect(_io_cb)
示例7: __init__
def __init__(self, filepath, parent=None):
super().__init__(parent)
self._filepath = filepath
# We open as R/W so we never get EOF and have to reopen the pipe.
# See http://www.outflux.net/blog/archives/2008/03/09/using-select-on-a-fifo/
# We also use os.open and os.fdopen rather than built-in open so we
# can add O_NONBLOCK.
fd = os.open(filepath, os.O_RDWR | os.O_NONBLOCK) # pylint: disable=no-member
self.fifo = os.fdopen(fd, "r")
self._notifier = QSocketNotifier(fd, QSocketNotifier.Read, self)
self._notifier.activated.connect(self.read_line)
示例8: init_zocp
def init_zocp(self):
self.z = ZOCP("QT UI TEST")
self.z.register_float("myFloat", 2.3, 'rw', 0, 5.0, 0.1)
self.notifier = QSocketNotifier(
self.z.inbox.getsockopt(zmq.FD),
QSocketNotifier.Read
)
self.notifier.setEnabled(True)
self.notifier.activated.connect(self.zocp_event)
self.z.on_modified = self.on_modified
self.z.start()
示例9: __init__
def __init__(self, parent, reactor, watcher, socketType):
QObject.__init__(self, parent)
self.reactor = reactor
self.watcher = watcher
fd = watcher.fileno()
self.notifier = QSocketNotifier(fd, socketType, parent)
self.notifier.setEnabled(True)
if socketType == QSocketNotifier.Read:
self.fn = self.read
else:
self.fn = self.write
self.notifier.activated.connect(self.fn)
示例10: _QtFIFOReader
class _QtFIFOReader(QObject):
"""A FIFO reader based on a QSocketNotifier."""
got_line = pyqtSignal(str)
def __init__(self, filepath, parent=None):
super().__init__(parent)
self._filepath = filepath
# We open as R/W so we never get EOF and have to reopen the pipe.
# See http://www.outflux.net/blog/archives/2008/03/09/using-select-on-a-fifo/
# We also use os.open and os.fdopen rather than built-in open so we
# can add O_NONBLOCK.
# pylint: disable=no-member,useless-suppression
fd = os.open(filepath, os.O_RDWR | os.O_NONBLOCK)
self.fifo = os.fdopen(fd, 'r')
self._notifier = QSocketNotifier(fd, QSocketNotifier.Read, self)
self._notifier.activated.connect(self.read_line)
@pyqtSlot()
def read_line(self):
"""(Try to) read a line from the FIFO."""
log.procs.debug("QSocketNotifier triggered!")
self._notifier.setEnabled(False)
for line in self.fifo:
self.got_line.emit(line.rstrip('\r\n'))
self._notifier.setEnabled(True)
def cleanup(self):
"""Clean up so the FIFO can be closed."""
self._notifier.setEnabled(False)
示例11: QTZOCPNode
class QTZOCPNode(QWidget):
def __init__(self):
super(QTZOCPNode, self).__init__()
self.qle = QTextEdit(self)
self.qle.move(1, 1)
self.qle.resize(640,480)
self.init_zocp()
self.show()
def init_zocp(self):
self.z = ZOCP("QT UI TEST")
self.z.register_float("myFloat", 2.3, 'rw', 0, 5.0, 0.1)
self.notifier = QSocketNotifier(
self.z.inbox.getsockopt(zmq.FD),
QSocketNotifier.Read
)
self.notifier.setEnabled(True)
self.notifier.activated.connect(self.zocp_event)
self.z.on_modified = self.on_modified
self.z.start()
def zocp_event(self):
print("ZOCP EVENT START")
self.z.run_once(0)
print("ZOCP EVENT END")
def on_modified(self, peer, name, data, *args, **kwargs):
t = self.qle.toPlainText()
t = "{0}\n{1}".format(data, t)
self.qle.setPlainText(t)
def closeEvent(self, *args):
print(args)
self.z.stop()
del self.z
示例12: _QtFIFOReader
class _QtFIFOReader(QObject):
"""A FIFO reader based on a QSocketNotifier.
Attributes:
_filepath: The path to the opened FIFO.
_fifo: The Python file object for the FIFO.
_notifier: The QSocketNotifier used.
Signals:
got_line: Emitted when a whole line arrived.
"""
got_line = pyqtSignal(str)
def __init__(self, filepath, parent=None):
super().__init__(parent)
self._filepath = filepath
# We open as R/W so we never get EOF and have to reopen the pipe.
# See http://www.outflux.net/blog/archives/2008/03/09/using-select-on-a-fifo/
# We also use os.open and os.fdopen rather than built-in open so we
# can add O_NONBLOCK.
# pylint: disable=no-member,useless-suppression
fd = os.open(filepath, os.O_RDWR | os.O_NONBLOCK)
# pylint: enable=no-member,useless-suppression
self._fifo = os.fdopen(fd, 'r')
self._notifier = QSocketNotifier(fd, QSocketNotifier.Read, self)
self._notifier.activated.connect(self.read_line)
@pyqtSlot()
def read_line(self):
"""(Try to) read a line from the FIFO."""
log.procs.debug("QSocketNotifier triggered!")
try:
self._notifier.setEnabled(False)
try:
for line in self._fifo:
self.got_line.emit(line.rstrip('\r\n'))
self._notifier.setEnabled(True)
except UnicodeDecodeError as e:
log.misc.error("Invalid unicode in userscript output: {}"
.format(e))
except RuntimeError as e:
# For unknown reasons, read_line can still get called after the
# QSocketNotifier was already deleted...
log.procs.debug("While reading userscript output: {}".format(e))
def cleanup(self):
"""Clean up so the FIFO can be closed."""
self._notifier.setEnabled(False)
for line in self._fifo:
self.got_line.emit(line.rstrip('\r\n'))
self._fifo.close()
示例13: TwistedSocketNotifier
class TwistedSocketNotifier(QObject):
"""
Connection between an fd event and reader/writer callbacks.
"""
activated = pyqtSignal(int)
def __init__(self, parent, reactor, watcher, socketType):
QObject.__init__(self, parent)
self.reactor = reactor
self.watcher = watcher
fd = watcher.fileno()
self.notifier = QSocketNotifier(fd, socketType, parent)
self.notifier.setEnabled(True)
if socketType == QSocketNotifier.Read:
self.fn = self.read
else:
self.fn = self.write
self.notifier.activated.connect(self.fn)
def shutdown(self):
self.notifier.setEnabled(False)
self.notifier.activated.disconnect(self.fn)
self.fn = self.watcher = None
self.notifier.deleteLater()
self.deleteLater()
def read(self, fd):
if not self.watcher:
return
w = self.watcher
# doRead can cause self.shutdown to be called so keep
# a reference to self.watcher
def _read():
#Don't call me again, until the data has been read
self.notifier.setEnabled(False)
why = None
try:
why = w.doRead()
inRead = True
except:
inRead = False
log.err()
why = sys.exc_info()[1]
if why:
self.reactor._disconnectSelectable(w, why, inRead)
elif self.watcher:
self.notifier.setEnabled(True)
# Re enable notification following sucessfull read
self.reactor._iterate(fromqt=True)
log.callWithLogger(w, _read)
def write(self, sock):
if not self.watcher:
return
w = self.watcher
def _write():
why = None
self.notifier.setEnabled(False)
try:
why = w.doWrite()
except:
log.err()
why = sys.exc_info()[1]
if why:
self.reactor._disconnectSelectable(w, why, False)
elif self.watcher:
self.notifier.setEnabled(True)
self.reactor._iterate(fromqt=True)
log.callWithLogger(w, _write)
示例14: SignalHandler
class SignalHandler(QObject):
"""Handler responsible for handling OS signals (SIGINT, SIGTERM, etc.).
Attributes:
_app: The QApplication instance.
_quitter: The Quitter instance.
_activated: Whether activate() was called.
_notifier: A QSocketNotifier used for signals on Unix.
_timer: A QTimer used to poll for signals on Windows.
_orig_handlers: A {signal: handler} dict of original signal handlers.
_orig_wakeup_fd: The original wakeup filedescriptor.
"""
def __init__(self, *, app, quitter, parent=None):
super().__init__(parent)
self._app = app
self._quitter = quitter
self._notifier = None
self._timer = usertypes.Timer(self, 'python_hacks')
self._orig_handlers = {}
self._activated = False
self._orig_wakeup_fd = None
def activate(self):
"""Set up signal handlers.
On Windows this uses a QTimer to periodically hand control over to
Python so it can handle signals.
On Unix, it uses a QSocketNotifier with os.set_wakeup_fd to get
notified.
"""
self._orig_handlers[signal.SIGINT] = signal.signal(
signal.SIGINT, self.interrupt)
self._orig_handlers[signal.SIGTERM] = signal.signal(
signal.SIGTERM, self.interrupt)
if os.name == 'posix' and hasattr(signal, 'set_wakeup_fd'):
# pylint: disable=import-error,no-member,useless-suppression
import fcntl
read_fd, write_fd = os.pipe()
for fd in [read_fd, write_fd]:
flags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
self._notifier = QSocketNotifier(read_fd, QSocketNotifier.Read,
self)
self._notifier.activated.connect(self.handle_signal_wakeup)
self._orig_wakeup_fd = signal.set_wakeup_fd(write_fd)
else:
self._timer.start(1000)
self._timer.timeout.connect(lambda: None)
self._activated = True
def deactivate(self):
"""Deactivate all signal handlers."""
if not self._activated:
return
if self._notifier is not None:
self._notifier.setEnabled(False)
rfd = self._notifier.socket()
wfd = signal.set_wakeup_fd(self._orig_wakeup_fd)
os.close(rfd)
os.close(wfd)
for sig, handler in self._orig_handlers.items():
signal.signal(sig, handler)
self._timer.stop()
self._activated = False
@pyqtSlot()
def handle_signal_wakeup(self):
"""Handle a newly arrived signal.
This gets called via self._notifier when there's a signal.
Python will get control here, so the signal will get handled.
"""
log.destroy.debug("Handling signal wakeup!")
self._notifier.setEnabled(False)
read_fd = self._notifier.socket()
try:
os.read(read_fd, 1)
except OSError:
log.destroy.exception("Failed to read wakeup fd.")
self._notifier.setEnabled(True)
def _log_later(self, *lines):
"""Log the given text line-wise with a QTimer."""
for line in lines:
QTimer.singleShot(0, functools.partial(log.destroy.info, line))
def interrupt(self, signum, _frame):
"""Handler for signals to gracefully shutdown (SIGINT/SIGTERM).
This calls shutdown and remaps the signal to call
interrupt_forcefully the next time.
"""
signal.signal(signal.SIGINT, self.interrupt_forcefully)
signal.signal(signal.SIGTERM, self.interrupt_forcefully)
# Signals can arrive anywhere, so we do this in the main thread
#.........这里部分代码省略.........
示例15: Application
class Application(QApplication):
"""Main application instance.
Attributes:
_args: ArgumentParser instance.
_shutting_down: True if we're currently shutting down.
_quit_status: The current quitting status.
_crashdlg: The crash dialog currently open.
_crashlogfile: A file handler to the fatal crash logfile.
_event_filter: The EventFilter for the application.
_signal_notifier: A QSocketNotifier used for signals on Unix.
_signal_timer: A QTimer used to poll for signals on Windows.
geometry: The geometry of the last closed main window.
"""
def __init__(self, args):
"""Constructor.
Args:
Argument namespace from argparse.
"""
# pylint: disable=too-many-statements
self._quit_status = {
'crash': True,
'tabs': False,
'main': False,
}
self.geometry = None
self._shutting_down = False
self._crashdlg = None
self._crashlogfile = None
qt_args = qtutils.get_args(args)
log.init.debug("Qt arguments: {}, based on {}".format(qt_args, args))
super().__init__(qt_args)
sys.excepthook = self._exception_hook
self._args = args
objreg.register('args', args)
objreg.register('app', self)
if self._args.version:
print(version.version())
print()
print()
print(qutebrowser.__copyright__)
print()
print(version.GPL_BOILERPLATE.strip())
sys.exit(0)
try:
sent = ipc.send_to_running_instance(self._args.command)
if sent:
sys.exit(0)
log.init.debug("Starting IPC server...")
ipc.init()
except ipc.IPCError as e:
text = ('{}\n\nMaybe another instance is running but '
'frozen?'.format(e))
msgbox = QMessageBox(QMessageBox.Critical, "Error while "
"connecting to running instance!", text)
msgbox.exec_()
# We didn't really initialize much so far, so we just quit hard.
sys.exit(1)
log.init.debug("Starting init...")
self.setQuitOnLastWindowClosed(False)
self.setOrganizationName("qutebrowser")
self.setApplicationName("qutebrowser")
self.setApplicationVersion(qutebrowser.__version__)
self._init_icon()
utils.actute_warning()
try:
self._init_modules()
except (OSError, UnicodeDecodeError) as e:
msgbox = QMessageBox(
QMessageBox.Critical, "Error while initializing!",
"Error while initializing: {}".format(e))
msgbox.exec_()
sys.exit(1)
QTimer.singleShot(0, self._process_args)
log.init.debug("Initializing eventfilter...")
self._event_filter = modeman.EventFilter(self)
self.installEventFilter(self._event_filter)
log.init.debug("Connecting signals...")
self._connect_signals()
log.init.debug("Setting up signal handlers...")
self._setup_signals()
QDesktopServices.setUrlHandler('http', self.open_desktopservices_url)
QDesktopServices.setUrlHandler('https', self.open_desktopservices_url)
QDesktopServices.setUrlHandler('qute', self.open_desktopservices_url)
log.init.debug("Init done!")
#.........这里部分代码省略.........