unify synchronous calling of twisted CLI commands

This commit is contained in:
Brian Warner 2016-03-02 00:51:21 -08:00
parent 4d405c8cef
commit 6d3d0c1cb3
2 changed files with 30 additions and 2 deletions

View File

@ -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()

View File

@ -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])