diff options
-rw-r--r-- | examples/copy_async.py | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/examples/copy_async.py b/examples/copy_async.py new file mode 100644 index 0000000..602ef47 --- /dev/null +++ b/examples/copy_async.py @@ -0,0 +1,77 @@ +import tempfile + +from gi.repository import GObject +from gi.repository import Gio +from gi.repository import GLib + +# Avoid "Fatal Python error: GC object already tracked" +# http://stackoverflow.com/questions/7496629/gstreamer-appsrc-causes-random-crashes +GObject.threads_init() + + +class FileTransfer(GObject.GObject): + _CHUNK_SIZE = 10240 + + def __init__(self, input_stream, output_stream): + GObject.GObject.__init__(self) + + self._input_stream = input_stream + self._output_stream = output_stream + self._buffer = GLib.Bytes.new([]) + self._buffer = GLib.ByteArray() + + def start(self): + self._input_stream.read_bytes_async( + self._CHUNK_SIZE, GLib.PRIORITY_LOW, + None, self.__read_async_cb, None) + + def __read_async_cb(self, input_stream, result, user_data=None): + data = input_stream.read_bytes_finish(result) + print 'Read Size:', data, 'Type:', type(data) + print 'Result:', result, 'Propagate ERROR:', result.propagate_error() + + if data is None: + # TODO: an error occured. Report something + print 'An error occured' + elif data.get_size() == 0: + # We read the file completely + print 'Closing the File.' + self._input_stream.close(None) + else: + self._input_stream.read_bytes_async( + self._CHUNK_SIZE, GLib.PRIORITY_LOW, + None, self.__read_async_cb, None) + self._write_next_buffer(data) + + def __write_async_cb(self, output_stream, result, user_data=None): + self._output_stream.write_bytes_finish(result) + + if not self._output_stream.has_pending() and \ + not self._input_stream.has_pending(): + output_stream.close(None) + print 'DONE' + loop.quit() + else: + self._write_next_buffer() + + def _write_next_buffer(self, data): + + if not self._output_stream.has_pending(): + self._output_stream.write_bytes_async( + data, GLib.PRIORITY_LOW, None, self.__write_async_cb, + None) + + +test_file_name = '/home/humitos/test.py' +test_input_stream = Gio.File.new_for_path(test_file_name).read(None) +PATH = tempfile.mkstemp()[1] +print PATH + +test_output_stream = Gio.File.new_for_path(PATH)\ + .append_to(Gio.FileCreateFlags.PRIVATE, None) + +splicer = FileTransfer(test_input_stream, test_output_stream) +splicer.start() + +loop = GObject.MainLoop() +loop.run() |