Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions Doc/library/tkinter.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6847,6 +6847,7 @@ Only one handler may be registered per file descriptor. Example code::
widget.tk.deletefilehandler(file)

This feature is not available on Windows.
For portable code, use :ref:`channels <tkinter-channels>` instead.

Since you don't know how many bytes are available for reading, you may not
want to use the :class:`~io.BufferedIOBase` or :class:`~io.TextIOBase`
Expand All @@ -6873,6 +6874,112 @@ use raw reads or ``os.read(file.fileno(), maxbytecount)``.
Unregisters a file handler.


.. _tkinter-channels:

Channels
^^^^^^^^

A channel lets the Tk mainloop do the I/O on a file, a pipe or a socket,
and call a handler when data can be read or written.
Unlike file handlers, channels work on all platforms, including Windows.
Example code::

import tkinter
widget = tkinter.Tk()
channel = widget.tk.createchannel(sock, 'rw')

def callback(channel, mask):
data = channel.read()
if data == b'':
channel.close()
elif data is not None:
...

channel.createhandler(tkinter.READABLE, callback)

The channel uses a duplicate of the file descriptor, the handle or the socket,
so closing the channel does not close the original object, and vice versa.
But Tcl may read ahead from the duplicate,
so do all I/O through the channel once it is created.
The duplicate shares the blocking mode with the original,
so the original socket, and on POSIX also the original file or pipe,
is switched to non-blocking mode and stays in it after the channel is closed.
Closing the channel shuts down reading from a socket,
so the original socket can still send but no longer receive data.


.. method:: Widget.tk.createchannel(file, mode='r', /)

Create a channel and return it as a :class:`!tkchannel` object.
*file* is a :class:`socket.socket` object,
an object with a :meth:`~io.IOBase.fileno` method,
or an integer file descriptor.
*mode* is ``'r'``, ``'w'`` or ``'rw'``.
Only stream sockets, such as TCP or UNIX sockets, are supported.
On Windows, pass the socket object, not the result of its
:meth:`~socket.socket.fileno` method.

The channel is binary and non-blocking.

.. versionadded:: next


.. method:: tkchannel.read(size=-1, /)

Read up to *size* bytes, or all available bytes if *size* is negative.
Return ``b''`` at end of file and ``None`` if no data is available.


.. method:: tkchannel.write(data, /)

Write the :term:`bytes-like object` *data*.
Data which cannot be written at once is written in the background.


.. method:: tkchannel.flush()

Flush the output buffer.


.. method:: tkchannel.eof()

Return ``True`` if the last read reached the end of file.


.. method:: tkchannel.createhandler(mask, func, /)

Register the handler callback function *func*,
replacing the previous handler, if any.
*mask* is an ORed combination of :data:`READABLE` and :data:`WRITABLE`.
The callback is called as follows::

callback(channel, mask)


.. method:: tkchannel.deletehandler()

Unregister the handler.


.. method:: tkchannel.close()

Close the channel.
The original file, pipe or socket stays open.
Channels are also context managers which close the channel on exit.


.. attribute:: tkchannel.name

The name of the channel in Tcl,
which can be passed to Tcl commands and Tk options which take a channel,
such as the *channel* option of :meth:`Canvas.postscript`.


.. attribute:: tkchannel.closed

``True`` if the channel is closed.


.. data:: READABLE
WRITABLE
EXCEPTION
Expand Down
7 changes: 7 additions & 0 deletions Doc/whatsnew/3.16.rst
Original file line number Diff line number Diff line change
Expand Up @@ -989,6 +989,13 @@ tkinter
the :class:`~tkinter.Text` widget.
(Contributed by Serhiy Storchaka in :gh:`159301`.)

* Added support for Tcl :ref:`channels <tkinter-channels>`.
A channel lets the Tk mainloop do the I/O on a file, a pipe or a socket,
and call a handler when data can be read or written.
Unlike :ref:`file handlers <tkinter-file-handlers>`,
channels also work on Windows.
(Contributed by Serhiy Storchaka in :gh:`162537`.)


turtle
------
Expand Down
193 changes: 193 additions & 0 deletions Lib/test/test_tcl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import subprocess
import sys
import os
import socket
import threading
from test import support
from test.support import import_helper
Expand Down Expand Up @@ -876,6 +877,198 @@ def test_new_tcl_obj(self):
support.check_disallow_instantiation(self, _tkinter.TkappType)


class ChannelTest(unittest.TestCase):

def setUp(self):
self.tk = Tcl().tk

def wait(self, channel, mask):
events = []
channel.createhandler(mask, lambda chan, m: events.append(m))
try:
for _ in range(1000):
if events:
break
self.tk.dooneevent()
else:
self.fail('no event')
finally:
channel.deletehandler()
self.assertEqual(events[0] & mask, mask)

def test_pipe(self):
r, w = os.pipe()
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
with self.tk.createchannel(r) as channel:
self.assertFalse(channel.closed)
self.assertIsInstance(channel.name, str)
self.assertIsNone(channel.read())
os.write(w, b'ab\0\xff')
self.wait(channel, tkinter.READABLE)
self.assertEqual(channel.read(2), b'ab')
self.assertEqual(channel.read(), b'\0\xff')
self.assertIsNone(channel.read())
self.assertFalse(channel.eof())
self.assertTrue(channel.closed)
# The original file descriptor is still open.
os.write(w, b'x')
self.assertEqual(os.read(r, 1), b'x')

def test_eof(self):
r, w = os.pipe()
self.addCleanup(os.close, r)
with self.tk.createchannel(r) as channel:
os.write(w, b'x')
os.close(w)
self.wait(channel, tkinter.READABLE)
self.assertEqual(channel.read(), b'x')
self.assertEqual(channel.read(), b'')
self.assertTrue(channel.eof())

def test_write(self):
r, w = os.pipe()
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
with self.tk.createchannel(w, 'w') as channel:
self.wait(channel, tkinter.WRITABLE)
channel.write(b'ab\0\xff')
channel.write(bytearray(b'c'))
channel.flush()
self.assertEqual(os.read(r, 10), b'ab\0\xffc')

def test_socket(self):
a, b = socket.socketpair()
self.addCleanup(a.close)
self.addCleanup(b.close)
with self.tk.createchannel(a, 'rw') as channel:
channel.write(b'ping')
channel.flush()
self.assertEqual(b.recv(10), b'ping')
b.send(b'pong')
self.wait(channel, tkinter.READABLE)
self.assertEqual(channel.read(), b'pong')
# The original socket is still open.
a.send(b'x')
self.assertEqual(b.recv(1), b'x')

def test_handler(self):
r, w = os.pipe()
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
channel = self.tk.createchannel(r)
self.addCleanup(channel.close)
calls = []
def handler(chan, mask):
calls.append((chan, mask))
chan.read()
chan.deletehandler()
channel.createhandler(tkinter.READABLE, handler)
os.write(w, b'x')
for _ in range(1000):
if calls:
break
self.tk.dooneevent()
self.assertEqual(calls, [(channel, tkinter.READABLE)])
# Deleting a deleted handler is a no-op.
channel.deletehandler()

def test_handler_keeps_channel_alive(self):
r, w = os.pipe()
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
calls = []
def handler(chan, mask):
calls.append(chan.read())
chan.close()
self.tk.createchannel(r).createhandler(tkinter.READABLE, handler)
support.gc_collect()
os.write(w, b'x')
for _ in range(1000):
if calls:
break
self.tk.dooneevent()
self.assertEqual(calls, [b'x'])

def test_close_from_tcl(self):
r, w = os.pipe()
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
with self.tk.createchannel(w, 'w') as channel:
self.tk.call('puts', '-nonewline', channel.name, 'ab')
self.tk.call('flush', channel.name)
self.assertEqual(os.read(r, 10), b'ab')
# Closing it in Tcl only unregisters the name.
self.tk.call('close', channel.name)
self.assertRaises(TclError, self.tk.call, 'flush', channel.name)
channel.write(b'cd')
channel.flush()
self.assertEqual(os.read(r, 10), b'cd')

def test_closed(self):
r, w = os.pipe()
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
channel = self.tk.createchannel(r)
name = channel.name
channel.close()
channel.close()
self.assertTrue(channel.closed)
self.assertRaises(TclError, self.tk.call, 'chan', 'configure', name)
for meth, *args in [('read',), ('write', b'x'), ('flush',),
('eof',), ('deletehandler',),
('createhandler', tkinter.READABLE, print)]:
with self.subTest(meth):
self.assertRaises(ValueError, getattr(channel, meth), *args)
self.assertIn('closed', repr(channel))

def test_dealloc_closes(self):
r, w = os.pipe()
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
name = self.tk.createchannel(r).name
support.gc_collect()
self.assertRaises(TclError, self.tk.call, 'chan', 'configure', name)

def test_bad_arguments(self):
r, w = os.pipe()
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
for mode in '', 'x', 'rr', 'a':
with self.subTest(mode=mode):
self.assertRaises(ValueError, self.tk.createchannel, r, mode)
self.assertRaises(TypeError, self.tk.createchannel, 'spam')
self.assertRaises(OSError, self.tk.createchannel, os_helper.make_bad_fd())
with self.tk.createchannel(r) as channel:
self.assertRaises(TypeError, channel.createhandler,
tkinter.READABLE, 'spam')
for mask in 0, tkinter.EXCEPTION, tkinter.READABLE | 0x100:
with self.subTest(mask=mask):
self.assertRaises(ValueError, channel.createhandler,
mask, print)
self.assertRaises(TypeError, channel.write, 'spam')

@unittest.skipIf(sys.platform == 'win32', 'requires POSIX')
def test_blocking(self):
# The original file shares the blocking mode with the duplicate.
r, w = os.pipe()
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
self.assertTrue(os.get_blocking(r))
with self.tk.createchannel(r):
self.assertFalse(os.get_blocking(r))
self.assertFalse(os.get_blocking(r))

@support.cpython_only
def test_dealloc_with_exception(self):
r, w = os.pipe()
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
# The channel is deallocated while the exception is set.
with self.assertRaises(ZeroDivisionError):
[self.tk.createchannel(r), 1/0]


class BigmemTclTest(unittest.TestCase):

def setUp(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Added support for Tcl :ref:`channels <tkinter-channels>` in :mod:`tkinter`.
A channel lets the Tk mainloop do the I/O on a file, a pipe or a socket, and
call a handler when data can be read or written. Unlike file handlers,
channels also work on Windows.
Loading
Loading