本文整理汇总了Python中PyQt5.QtCore.QSocketNotifier.setEnabled方法的典型用法代码示例。如果您正苦于以下问题:Python QSocketNotifier.setEnabled方法的具体用法?Python QSocketNotifier.setEnabled怎么用?Python QSocketNotifier.setEnabled使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtCore.QSocketNotifier
的用法示例。
在下文中一共展示了QSocketNotifier.setEnabled方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: FileListStream
# 需要导入模块: from PyQt5.QtCore import QSocketNotifier [as 别名]
# 或者: from PyQt5.QtCore.QSocketNotifier import setEnabled [as 别名]
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: XMMSConnector
# 需要导入模块: from PyQt5.QtCore import QSocketNotifier [as 别名]
# 或者: from PyQt5.QtCore.QSocketNotifier import setEnabled [as 别名]
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()
示例3: register_io
# 需要导入模块: from PyQt5.QtCore import QSocketNotifier [as 别名]
# 或者: from PyQt5.QtCore.QSocketNotifier import setEnabled [as 别名]
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)
示例4: _QtFIFOReader
# 需要导入模块: from PyQt5.QtCore import QSocketNotifier [as 别名]
# 或者: from PyQt5.QtCore.QSocketNotifier import setEnabled [as 别名]
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)
示例5: QTZOCPNode
# 需要导入模块: from PyQt5.QtCore import QSocketNotifier [as 别名]
# 或者: from PyQt5.QtCore.QSocketNotifier import setEnabled [as 别名]
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
示例6: _QtFIFOReader
# 需要导入模块: from PyQt5.QtCore import QSocketNotifier [as 别名]
# 或者: from PyQt5.QtCore.QSocketNotifier import setEnabled [as 别名]
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()
示例7: TwistedSocketNotifier
# 需要导入模块: from PyQt5.QtCore import QSocketNotifier [as 别名]
# 或者: from PyQt5.QtCore.QSocketNotifier import setEnabled [as 别名]
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)
示例8: SignalHandler
# 需要导入模块: from PyQt5.QtCore import QSocketNotifier [as 别名]
# 或者: from PyQt5.QtCore.QSocketNotifier import setEnabled [as 别名]
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
#.........这里部分代码省略.........
示例9: Application
# 需要导入模块: from PyQt5.QtCore import QSocketNotifier [as 别名]
# 或者: from PyQt5.QtCore.QSocketNotifier import setEnabled [as 别名]
#.........这里部分代码省略.........
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)
@pyqtSlot()
def _handle_signal_wakeup(self):
"""Handle a newly arrived signal.
This gets called via self._signal_notifier when there's a signal.
Python will get control here, so the signal will get handled.
"""
log.destroy.debug("Handling signal wakeup!")
self._signal_notifier.setEnabled(False)
read_fd = self._signal_notifier.socket()
try:
os.read(read_fd, 1)
except OSError:
log.destroy.exception("Failed to read wakeup fd.")
self._signal_notifier.setEnabled(True)
def _connect_signals(self):
"""Connect all signals to their slots."""
config_obj = objreg.get('config')
self.lastWindowClosed.connect(self.on_last_window_closed)
config_obj.style_changed.connect(style.get_stylesheet.cache_clear)
self.focusChanged.connect(self.on_focus_changed)
self.focusChanged.connect(message.on_focus_changed)
def _get_widgets(self):
"""Get a string list of all widgets."""
widgets = self.allWidgets()
widgets.sort(key=repr)
return [repr(w) for w in widgets]
def _get_pyqt_objects(self, lines, obj, depth=0):
"""Recursive method for get_all_objects to get Qt objects."""
for kid in obj.findChildren(QObject):
lines.append(' ' * depth + repr(kid))
self._get_pyqt_objects(lines, kid, depth + 1)
def get_all_objects(self):
"""Get all children of an object recursively as a string."""
output = ['']
widget_lines = self._get_widgets()
widget_lines = [' ' + e for e in widget_lines]