Here are the examples of the python api twisted.internet.reactor.run taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
112 Examples
3
Example 1
def poetry_main():
addresses = parse_args()
start = datetime.datetime.now()
sockets = [PoetrySocket(i + 1, addr) for i, addr in enumerate(addresses)]
from twisted.internet import reactor
reactor.run()
elapsed = datetime.datetime.now() - start
for i, sock in enumerate(sockets):
print 'Task %d: %d bytes of poetry' % (i + 1, len(sock.poem))
print 'Got %d poems in %s' % (len(addresses), elapsed)
3
Example 2
def run(callback):
db = Db()
datalib.db = db
init = db.startService()
init.addCallback(callback)
reactor.run()
3
Example 3
def SQLGet(cs, query, columns):
from SQLPlugin import SQLPlugin
sp = SQLPlugin()
sp.tables = {'t': (query, {}, cs, columns)}
cl = SQLClient(device=None, plugins=[sp,])
cl.run()
reactor.run()
for plugin, result in cl.getResults():
if plugin == sp and 't' in result:
return result['t']
return result
3
Example 4
def start(self):
""" Start the application. """
started = super(TwistedApplication, self).start()
# Don't start the event loop if the start was vetoed.
if started:
from twisted.internet import reactor
logger.debug('---------- reactor starting ----------')
reactor.run()
return started
3
Example 5
def getmessages(self):
parser = argparse.ArgumentParser(
description='Returns a list of your messages in json format',
usage='''usage:
subspace getmessages''')
args = parser.parse_args(sys.argv[2:])
d = proxy.callRemote('getmessages')
d.addCallbacks(printValue, printError)
reactor.run()
3
Example 6
def run(self, target_furl):
target_tubid = SturdyRef(target_furl).getTubRef().getTubID()
d = fireEventually(target_furl)
d.addCallback(self.start, target_tubid)
d.addErrback(self._error)
print "starting.."
reactor.run()
3
Example 7
Project: bitmask_client Source File: backend.py
def run(self):
"""
Start the ZMQ server and run the loop to handle requests.
"""
self._signaler.start()
self._frontend_checker = task.LoopingCall(self._check_frontend_alive)
self._frontend_checker.start(self.PING_INTERVAL)
logger.debug("Starting Twisted reactor.")
reactor.run()
logger.debug("Finished Twisted reactor.")
3
Example 8
def main(argv):
# Parse options
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-a", "--host", default="", help="address to listen on")
parser.add_argument("-p", "--port", default=25565, type=int, help="port to listen on")
args = parser.parse_args(argv)
# Create factory
factory = AuthFactory()
# Listen
factory.listen(args.host, args.port)
reactor.run()
3
Example 9
def run(url, stream_name='livestream', audio_codec=None, video_codec=None,
audio_bitrate=64, video_bitrate=400, samplerate=44100,
framerate=Fraction('15/1'), channels=1,
width=320, height=240, keyframe_interval=5.0, view=False,
view_window=None):
src = NewGstSource(audio_bitrate, video_bitrate,
samplerate, channels, framerate, width, height,
keyframe_interval, audio_codec=audio_codec,
video_codec=video_codec, view=view,
view_window=view_window)
f = connect_client_factory(url, OneTimeAppFactory,
SimplePublishingApp,
src,
stream_name)
reactor.run()
3
Example 10
Project: nodeset.core Source File: pure.py
def client():
stats = Stats()
c = protocol.ClientCreator(reactor, DumbProto)
c.connectTCP("localhost", 5333).addCallback(gotProtocol, stats, 3000)
reactor.run()
3
Example 11
def start(self):
"""
Start the DelugeWeb server
"""
if self.socket:
log.warn('DelugeWeb is already running and cannot be started')
return
log.info('Starting webui server at PID %s', os.getpid())
if self.https:
self.start_ssl()
else:
self.start_normal()
component.get('Web').enable()
if self.daemon:
reactor.run()
3
Example 12
def getinfo(self):
parser = argparse.ArgumentParser(
description="Returns an object containing various state info",
usage='''usage:
subspace getinfo''')
args = parser.parse_args(sys.argv[2:])
d = proxy.callRemote('getinfo')
d.addCallbacks(printValue, printError)
reactor.run()
3
Example 13
Project: vertex Source File: q2qclient.py
def start(self, portno=None):
import sys
lfname = self['logfile']
if lfname == '-':
lf = sys.stdout
else:
lf = file(os.path.expanduser(lfname), 'ab+')
log.startLogging(lf,
setStdout=False)
srv = self.getService()
from twisted.application.app import startApplication
startApplication(srv, False)
reactor.run()
3
Example 14
Project: django-dynamic-scraper Source File: scraper_test.py
def run_checker_test(self, id):
kwargs = {
'id': id,
}
self.checker_test = CheckerTest(**kwargs)
self.checker_test.conf['RUN_TYPE'] = 'TASK'
self.checker_test.conf['DO_ACTION'] = True
self.checker_test.conf['LOG_ENABLED'] = False
self.checker_test.conf['LOG_LEVEL'] = 'DEBUG'
self.crawler.crawl(self.checker_test)
self.crawler.start()
log.start(loglevel="DEBUG", logstdout=True)
reactor.run()
3
Example 15
def main(argv):
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("host")
parser.add_argument("-p", "--port", default=25565, type=int)
args = parser.parse_args(argv)
factory = PingFactory()
factory.connect(args.host, args.port, "status")
reactor.run()
3
Example 16
def run():
config = MyOptions()
try:
config.parseOptions()
except usage.UsageError, e:
print str(e)
print str(config)
sys.exit(1)
run_gtk2(config)
from twisted.internet import reactor
reactor.run()
3
Example 17
Project: ants Source File: transporttest.py
def test(self):
setting = settings.Settings()
cluster = node.NodeManager(setting)
transport_test = transport.TransportManager(cluster)
ip = '127.0.0.1'
transport_test.run_server()
transport_test.run_client(ip, setting.get('TRANSPORT_PORT'))
SendRequestThread(transport_test, ip).start()
reactor.run()
3
Example 18
Project: pyorpg-client Source File: engine.py
def init(self):
ResourceManager.loadEverything()
g.soundEngine = SoundEngine()
g.soundEngine.loadSounds()
self.initConfig(g.dataPath + '/config.cfg')
self.setState(MENU_LOGIN)
pygame.display.flip()
self.gameLoop()
reactor.run()
3
Example 19
Project: scrapyrt Source File: cmdline.py
def execute():
sys.path.insert(0, os.getcwd())
arguments = parse_arguments()
if arguments.settings:
settings.setmodule(arguments.settings)
if arguments.set:
for name, value in arguments.set:
settings.set(name.upper(), value)
settings.set('PROJECT_SETTINGS', find_scrapy_project(arguments.project))
settings.freeze()
setup_logging()
application = get_application(arguments)
app.startApplication(application, save=False)
reactor.run()
3
Example 20
Project: socorro Source File: sb_pop3dnd.py
def start():
assert state.prepared, "Must prepare before starting"
# The asyncore stuff doesn't play nicely with twisted (or vice-versa),
# so put them in separate threads.
thread.start_new_thread(Dibbler.run, ())
reactor.run()
3
Example 21
Project: gemuo Source File: simple.py
def simple_run(run):
d = simple_login()
d.addCallback(run)
d.addCallback(simple_callback)
d.addErrback(simple_err)
reactor.run()
3
Example 22
Project: snmposter Source File: snmposter.py
def start(self):
for a in self.agents:
print "Starting %s on %s." % (a['filename'], a['ip'])
if os.uname()[0] == 'Darwin':
os.popen("ifconfig lo0 alias %s up" % (a['ip'],))
elif os.uname()[0] == 'Linux':
os.popen("/sbin/ip addr add %s dev lo" % (a['ip'],))
else:
print "WARNING: Unable to add loopback alias on this platform."
faker = SNMPoster(a['ip'], a['filename'])
faker.run()
daemonize()
reactor.run()
3
Example 23
Project: scrapyd Source File: script.py
def execute():
try:
config = _get_config()
except NotConfigured:
config = None
log.startLogging(sys.stderr)
application = get_application(config)
app.startApplication(application, False)
reactor.run()
3
Example 24
def getnew(self):
parser = argparse.ArgumentParser(
description="Returns messages that have not previously been returned by this command",
usage='''usage:
subspace getnew''')
args = parser.parse_args(sys.argv[2:])
d = proxy.callRemote('getnew')
d.addCallbacks(printValue, printError)
reactor.run()
3
Example 25
Project: locality-sensitive-hashing Source File: twistedtools.py
def threaded_reactor():
"""
Start the Twisted reactor in a separate thread, if not already done.
Returns the reactor.
The thread will automatically be destroyed when all the tests are done.
"""
global _twisted_thread
try:
from twisted.internet import reactor
except ImportError:
return None, None
if not _twisted_thread:
from twisted.python import threadable
from threading import Thread
_twisted_thread = Thread(target=lambda: reactor.run( \
installSignalHandlers=False))
_twisted_thread.setDaemon(True)
_twisted_thread.start()
return reactor, _twisted_thread
3
Example 26
Project: djangospider Source File: async_twisted.py
def RunMain(self):
try:
heartbeat=task.LoopingCall(self.add_url)
heartbeat.start(1)
reactor.run()
except KeyboardInterrupt:
pass
3
Example 27
Project: gateway Source File: gateway.py
def main(service):
application = GatewayApplication(service)
tornado.autoreload.start(ioloop)
application.listen(config.get('websocket-port', 8888))
#debug_console = DebugConsole(application)
reactor.run()
3
Example 28
Project: kamaelia_ Source File: RawServer_twisted.py
def listen_forever(self):
self.ident = thread.get_ident()
if self.listened:
UnimplementedWarning(_("listen_forever() should only be called once per reactor."))
self.listened = 1
l = task.LoopingCall(self.stop)
l.start(1)#, now = False)
if noSignals:
reactor.run(installSignalHandlers=False)
else:
reactor.run()
3
Example 29
def run(self):
if self.isSecure:
contextFactory = ssl.ClientContextFactory()
else:
contextFactory = None
self.connector = connectWS(self, contextFactory)
self.read_channel()
reactor.run(installSignalHandlers=True)
3
Example 30
def main(argv):
parser = ProfileCLI.make_parser()
parser.add_argument("host")
parser.add_argument("port", nargs='?', default=25565, type=int)
args = parser.parse_args(argv)
run(args)
reactor.run()
3
Example 31
Project: frikanalen Source File: run_queue.py
def handle(self, *args, **options):
pending_tasks = Task.objects.filter(status=Task.STATE_PENDING)
self.log.info("%d outstanding tasks" % (len(pending_tasks),))
if pending_tasks:
for task in pending_tasks:
self.run_task(task)
reactor.run()
3
Example 32
Project: woid Source File: top.py
def main():
service_crawlers = (
(crawlers.RedditCrawler(), FIVE_MINUTES),
(crawlers.MediumCrawler(), FIVE_MINUTES),
(crawlers.DiggCrawler(), FIVE_MINUTES),
(crawlers.HackerNewsCrawler(), FIVE_MINUTES),
(crawlers.GithubCrawler(), THIRTY_MINUTES),
(crawlers.NyTimesCrawler(), THIRTY_MINUTES)
)
for crawler in service_crawlers:
task.LoopingCall(crawler[0].run).start(crawler[1])
reactor.run()
3
Example 33
def main():
logging.basicConfig(level=logging.NOTSET)
class TestClient(CampfireClient):
pass
t = TestClient()
t.connect()
reactor.run()
3
Example 34
Project: pinder Source File: streaming.py
def start(username, password, room_id, callback, errback, start_reactor=False):
auth_header = 'Basic ' + base64.b64encode("%s:%s" % (username, password)).strip()
url = 'https://streaming.campfirenow.com/room/%s/live.json' % room_id
headers = Headers({
'User-Agent': [USER_AGENT],
'Authorization': [auth_header]})
# issue the request
agent = Agent(reactor)
d = agent.request('GET', url, headers, None)
d.addCallback(_get_response, callback, errback)
d.addBoth(_shutdown, errback)
if start_reactor:
reactor.run()
3
Example 35
Project: mythbox Source File: stdio.py
def runWithProtocol(klass):
fd = sys.__stdin__.fileno()
oldSettings = termios.tcgetattr(fd)
tty.setraw(fd)
try:
p = ServerProtocol(klass)
stdio.StandardIO(p)
reactor.run()
finally:
termios.tcsetattr(fd, termios.TCSANOW, oldSettings)
os.write(fd, "\r\x1bc\r")
3
Example 36
def run(self, options):
d = fireEventually(options)
d.addCallback(self.start)
d.addErrback(self._error)
print "starting.."
reactor.run()
3
Example 37
Project: lbry Source File: node_rpc_cli.py
def main():
parser = argparse.ArgumentParser(description="Send an rpc command to a dht node")
parser.add_argument("rpc_command",
help="The rpc command to send to the dht node")
parser.add_argument("--node_host",
help="The host of the node to connect to",
default="127.0.0.1")
parser.add_argument("--node_port",
help="The port of the node to connect to",
default="8888")
args = parser.parse_args()
connect_string = 'http://%s:%s' % (args.node_host, args.node_port)
proxy = Proxy(connect_string)
d = proxy.callRemote(args.rpc_command)
d.addCallbacks(print_value, print_error)
d.addBoth(lambda _: shut_down())
reactor.run()
3
Example 38
def main(argv):
# Parse options
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-a", "--listen-host", default="", help="address to listen on")
parser.add_argument("-p", "--listen-port", default=25565, type=int, help="port to listen on")
parser.add_argument("-b", "--connect-host", default="127.0.0.1", help="address to connect to")
parser.add_argument("-q", "--connect-port", default=25565, type=int, help="port to connect to")
args = parser.parse_args(argv)
# Create factory
factory = QuietDownstreamFactory()
factory.motd = "Proxy Server"
factory.connect_host = args.connect_host
factory.connect_port = args.connect_port
# Listen
factory.listen(args.listen_host, args.listen_port)
reactor.run()
3
Example 39
def start(self):
'''启动服务器
'''
log.msg('%s start...'%self.servername)
log.msg('%s pid: %s'%(self.servername,os.getpid()))
reactor.run()
3
Example 40
Project: ants Source File: webservicetest.py
def test(self):
cluster_info = cluster.ClusterInfo(name='test')
setting = settings.Settings()
crawl_manager = crawl.CrawlManager(setting, cluster_info)
web_service_management = webservice.WebServiceManager(8080, cluster_info, crawl_manager)
web_service_management.start()
reactor.run()
3
Example 41
def run(self):
self.clientApiHttpServer.setup()
self.replicationHttpsServer.setup()
self.pusher.setup()
if self.pidfile:
with open(self.pidfile, 'w') as pidfile:
pidfile.write(str(os.getpid()) + "\n")
twisted.internet.reactor.run()
3
Example 42
Project: pyrf Source File: simple_gui.py
def main():
name = None
if '-v' in sys.argv:
sys.argv.remove('-v')
logging.basicConfig(level=logging.DEBUG)
if '-d' in sys.argv:
d_index = sys.argv.index('-d')
name = sys.argv[d_index + 1]
del sys.argv[d_index:d_index + 2]
app = QtGui.QApplication(sys.argv)
qt4reactor.install() # requires QApplication to exist
# requires qt4reactor to be installed
if name:
ex = MainWindow(open(name, 'wb'))
else:
ex = MainWindow()
# late import because installReactor is being used
from twisted.internet import reactor
reactor.run()
3
Example 43
def run():
config.read()
config.LOG_DIRECTORY = "stdout"
log.startLogging(sys.stdout)
db = Db()
db.startService().addCallback(convert)
reactor.run()
3
Example 44
Project: PiIO.WS Source File: client.py
def main():
if USE_SSL:
uri_type = "wss"
else:
uri_type = "ws"
server_url = "%s://%s:%d/rpi/" % (uri_type, SERVER, PORT)
if DEBUG:
log.startLogging(sys.stdout)
#factory = WebSocketClientFactory(server_url, useragent=settings.RPI_USER_AGENT, debug=DEBUG)
factory = ReconnectingWebSocketClientFactory(server_url, useragent=settings.RPI_USER_AGENT, debug=DEBUG)
factory.protocol = RPIClientProtocol
connectWS(factory)
reactor.run()
3
Example 45
def main(argv):
# Parse options
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-a", "--host", default="", help="address to listen on")
parser.add_argument("-p", "--port", default=25565, type=int, help="port to listen on")
parser.add_argument("-m", "--message", default="We're down for maintenance",
help="message to kick users with")
args = parser.parse_args(argv)
# Create factory
factory = DowntimeFactory()
factory.motd = args.message
# Listen
factory.listen(args.host, args.port)
reactor.run()
3
Example 46
Project: pixelated-user-agent Source File: app_test_client.py
def run_on_a_thread(self, logfile='/tmp/app_test_client.log', port=4567, host='127.0.0.1'):
def _start():
self.listenTCP(port, host)
reactor.run()
process = multiprocessing.Process(target=_start)
process.start()
time.sleep(1)
return lambda: process.terminate()
3
Example 47
Project: beatserver Source File: server.py
def run(self):
"""
extract all schedules from beat_config files and feed into twisted task.
"""
for beat in self.beat_config:
message = self.beat_config[beat]['message']
channel_name = self.beat_config[beat]['channel_name']
schedule = self.beat_config[beat]['schedule']
sche = task.LoopingCall(self.run_task, channel_name, message)
sche.start(schedule.total_seconds())
logger.info("beatserver started")
reactor.run()
3
Example 48
def main(argv):
parser = ProfileCLI.make_parser()
parser.add_argument("host")
parser.add_argument("-p", "--port", default=25565, type=int)
args = parser.parse_args(argv)
run(args)
reactor.run()
3
Example 49
def run(self):
import os
from twisted.internet import reactor
global_config = {}
global_config['my_pid'] = os.getpid()
rtpc = Rtp_proxy_client_udp(global_config, ('127.0.0.1', 22226), None)
rtpc.rtpp_class = Rtp_proxy_client_udp
os.system('sockstat | grep -w %d' % global_config['my_pid'])
rtpc.send_command('Ib', self.gotreply)
reactor.run()
rtpc.reconnect(('localhost', 22226), ('0.0.0.0', 34222))
os.system('sockstat | grep -w %d' % global_config['my_pid'])
rtpc.send_command('V', self.gotreply)
reactor.run()
rtpc.reconnect(('localhost', 22226), ('127.0.0.1', 57535))
os.system('sockstat | grep -w %d' % global_config['my_pid'])
rtpc.send_command('V', self.gotreply)
reactor.run()
rtpc.shutdown()
3
Example 50
def _stream(self): # pragma: no cover
"""Runs in a sub-process to perform stream consumption"""
self.factory.protocol = LiveStream
self.factory.datasift = {
'on_open': self._on_open,
'on_close': self._on_close,
'on_message': self._on_message,
'send_message': None
}
if self.config.ssl:
from twisted.internet import ssl
options = ssl.optionsForClientTLS(hostname=WEBSOCKET_HOST.decode("utf-8"))
connectWS(self.factory, options)
else:
connectWS(self.factory)
reactor.run()