Ticket #4242: copy_async.py

File copy_async.py, 2.4 KB (added by humitos, 11 years ago)

Example about how to use Gio async (read & write) from Python

Line 
1import tempfile
2
3from gi.repository import GObject
4from gi.repository import Gio
5from gi.repository import GLib
6
7# Avoid "Fatal Python error: GC object already tracked"
8# http://stackoverflow.com/questions/7496629/gstreamer-appsrc-causes-random-crashes
9GObject.threads_init()
10
11
12class FileTransfer(GObject.GObject):
13    _CHUNK_SIZE = 10240
14
15    def __init__(self, input_stream, output_stream):
16        GObject.GObject.__init__(self)
17
18        self._input_stream = input_stream
19        self._output_stream = output_stream
20        self._buffer = GLib.Bytes.new([])
21        self._buffer = GLib.ByteArray()
22
23    def start(self):
24        self._input_stream.read_bytes_async(
25            self._CHUNK_SIZE, GLib.PRIORITY_LOW,
26            None, self.__read_async_cb, None)
27
28    def __read_async_cb(self, input_stream, result, user_data=None):
29        data = input_stream.read_bytes_finish(result)
30        print 'Read Size:', data, 'Type:', type(data)
31        print 'Result:', result, 'Propagate ERROR:', result.propagate_error()
32
33        if data is None:
34            # TODO: an error occured. Report something
35            print 'An error occured'
36        elif data.get_size() == 0:
37            # We read the file completely
38            print 'Closing the File.'
39            self._input_stream.close(None)
40        else:
41            self._input_stream.read_bytes_async(
42                self._CHUNK_SIZE, GLib.PRIORITY_LOW,
43                None, self.__read_async_cb, None)
44            self._write_next_buffer(data)
45
46    def __write_async_cb(self, output_stream, result, user_data=None):
47        self._output_stream.write_bytes_finish(result)
48
49        if not self._output_stream.has_pending() and \
50                not self._input_stream.has_pending():
51            output_stream.close(None)
52            print 'DONE'
53            loop.quit()
54        else:
55            self._write_next_buffer()
56
57    def _write_next_buffer(self, data):
58
59        if not self._output_stream.has_pending():
60            self._output_stream.write_bytes_async(
61                data, GLib.PRIORITY_LOW, None, self.__write_async_cb,
62                None)
63
64
65test_file_name = '/home/humitos/test.py'
66test_input_stream = Gio.File.new_for_path(test_file_name).read(None)
67PATH = tempfile.mkstemp()[1]
68print PATH
69
70test_output_stream = Gio.File.new_for_path(PATH)\
71    .append_to(Gio.FileCreateFlags.PRIVATE, None)
72
73splicer = FileTransfer(test_input_stream, test_output_stream)
74splicer.start()
75
76loop = GObject.MainLoop()
77loop.run()