From 6d3d0c1cb39682238203d48e48ea4ce60460e3d6 Mon Sep 17 00:00:00 2001 From: Brian Warner Date: Wed, 2 Mar 2016 00:51:21 -0800 Subject: [PATCH] unify synchronous calling of twisted CLI commands --- src/wormhole/scripts/cmd_receive_twisted.py | 23 +++++++++++++++++++++ src/wormhole/scripts/cmd_send_twisted.py | 9 ++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/wormhole/scripts/cmd_receive_twisted.py b/src/wormhole/scripts/cmd_receive_twisted.py index 487fc14..b8b97ba 100644 --- a/src/wormhole/scripts/cmd_receive_twisted.py +++ b/src/wormhole/scripts/cmd_receive_twisted.py @@ -1,5 +1,6 @@ from __future__ import print_function import io, json +from twisted.internet import reactor, defer from twisted.internet.defer import inlineCallbacks, returnValue from ..twisted.transcribe import Wormhole, WrongPasswordError from ..twisted.transit import TransitReceiver @@ -7,6 +8,28 @@ from .cmd_receive_blocking import BlockingReceiver, RespondError, APPID from ..errors import TransferError from .progress import ProgressPrinter +def receive_twisted_sync(args): + # try to use twisted.internet.task.react(f) here (but it calls sys.exit + # directly) + d = defer.Deferred() + # don't call receive_twisted() until after the reactor is running, so + # that if it raises an exception synchronously, we won't stop the reactor + # before it starts + reactor.callLater(0, d.callback, None) + d.addCallback(lambda _: receive_twisted(args)) + rc = [] + def _done(res): + rc.extend([True, res]) + reactor.stop() + def _err(f): + rc.extend([False, f.value]) + reactor.stop() + d.addCallbacks(_done, _err) + reactor.run() + if rc[0]: + return rc[1] + raise rc[1] + def receive_twisted(args): return TwistedReceiver(args).go() diff --git a/src/wormhole/scripts/cmd_send_twisted.py b/src/wormhole/scripts/cmd_send_twisted.py index ee61b72..75ceb09 100644 --- a/src/wormhole/scripts/cmd_send_twisted.py +++ b/src/wormhole/scripts/cmd_send_twisted.py @@ -1,7 +1,7 @@ from __future__ import print_function import io, json, binascii, six from twisted.protocols import basic -from twisted.internet import reactor +from twisted.internet import reactor, defer from twisted.internet.defer import inlineCallbacks, returnValue from ..errors import TransferError from .progress import ProgressPrinter @@ -11,9 +11,14 @@ from .send_common import (APPID, handle_zero, build_other_command, build_phase1_data) def send_twisted_sync(args): - d = send_twisted(args) # try to use twisted.internet.task.react(f) here (but it calls sys.exit # directly) + d = defer.Deferred() + # don't call send_twisted() until after the reactor is running, so + # that if it raises an exception synchronously, we won't stop the reactor + # before it starts + reactor.callLater(0, d.callback, None) + d.addCallback(lambda _: send_twisted(args)) rc = [] def _done(res): rc.extend([True, res])