示例#1
0
文件: run.py 项目: oscar810429/pndfs
def runApp(config):
	loadConfigurations(config, settings)
	
	if not sys.modules.has_key('twisted.internet.reactor'):
		from twisted.application.reactors import installReactor
		installReactor(settings.reactor)
	ApplicationRunner(config).run()
示例#2
0
def install_reactor(explicitReactor = None, verbose = False):
    """
    Install Twisted reactor.
    
    :param explicitReactor: If provided, install this reactor. Else, install optimal reactor.
    :type explicitReactor: obj
    :param verbose: If ``True``, print what happens.
    :type verbose: bool
    """
    import sys
    if explicitReactor:
        from twisted.application.reactors import installReactor
        print "Trying to install explicitly specified Twisted reactor '%s'" % explicitReactor
        try:
            installReactor(explicitReactor)
        except Exception as e:
            print 'Could not install Twisted reactor %s%s' % (explicitReactor, ' ["%s"]' % e if verbose else '')
            sys.exit(1)

    else:
        if verbose:
            print 'Automatically choosing optimal Twisted reactor'
        install_optimal_reactor(verbose)
    from twisted.internet import reactor
    if verbose:
        from twisted.python.reflect import qual
        print 'Running Twisted reactor %s' % qual(reactor.__class__)
    return reactor
示例#3
0
 def opt_reactor(self, shortName):
     """
     Which reactor to use (see --help-reactors for a list of possibilities)
     """
     # Actually actually actually install the reactor right at this very
     # moment, before any other code (for example, a sub-command plugin)
     # runs and accidentally imports and installs the default reactor.
     #
     # This could probably be improved somehow.
     try:
         installReactor(shortName)
     except NoSuchReactor:
         msg = (
             "The specified reactor does not exist: '%s'.\n"
             "See the list of available reactors with "
             "--help-reactors" % (shortName,)
         )
         raise usage.UsageError(msg)
     except Exception as e:
         msg = (
             "The specified reactor cannot be used, failed with error: "
             "%s.\nSee the list of available reactors with "
             "--help-reactors" % (e,)
         )
         raise usage.UsageError(msg)
     else:
         self["reactor"] = shortName
示例#4
0
def install_reactor(explicit_reactor=None,
                    verbose=False,
                    log=None,
                    require_optimal_reactor=True):
    """
    Install Twisted reactor.

    :param explicit_reactor: If provided, install this reactor. Else, install
        the optimal reactor.
    :type explicit_reactor: obj

    :param verbose: If ``True``, log (at level "info") the reactor that is
        in place afterwards.
    :type verbose: bool

    :param log: Explicit logging to this txaio logger object.
    :type log: obj

    :param require_optimal_reactor: If ``True`` and the desired reactor could not be installed,
        raise ``ReactorAlreadyInstalledError``, else fallback to another reactor.
    :type require_optimal_reactor: bool

    :returns: The Twisted reactor in place (`twisted.internet.reactor`).
    """
    if not log:
        log = txaio.make_logger()

    if explicit_reactor:
        # install explicitly given reactor
        #
        from twisted.application.reactors import installReactor
        if verbose:
            log.info(
                'Trying to install explicitly specified Twisted reactor "{reactor}" ..',
                reactor=explicit_reactor)
        try:
            installReactor(explicit_reactor)
        except:
            log.failure(
                'Could not install Twisted reactor {reactor}\n{log_failure.value}',
                reactor=explicit_reactor)
            sys.exit(1)
    else:
        # automatically choose optimal reactor
        #
        if verbose:
            log.info('Automatically choosing optimal Twisted reactor ..')
        install_optimal_reactor(require_optimal_reactor)

    # now the reactor is installed, import it
    from twisted.internet import reactor
    txaio.config.loop = reactor

    if verbose:
        from twisted.python.reflect import qual
        log.info('Running on Twisted reactor {reactor}',
                 reactor=qual(reactor.__class__))

    return reactor
示例#5
0
def install_optimal_reactor():
    """
   Try to install the optimal Twisted reactor for platform.
   """
    import sys

    if 'bsd' in sys.platform or sys.platform.startswith('darwin'):
        try:
            v = sys.version_info
            if v[0] == 1 or (v[0] == 2
                             and v[1] < 6) or (v[0] == 2 and v[1] == 6
                                               and v[2] < 5):
                raise Exception("Python version too old (%s)" % sys.version)
            from twisted.internet import kqreactor
            kqreactor.install()
        except Exception as e:
            print("""
   WARNING: Running on BSD or Darwin, but cannot use kqueue Twisted reactor.

    => %s

   To use the kqueue Twisted reactor, you will need:

     1. Python >= 2.6.5 or PyPy > 1.8
     2. Twisted > 12.0

   Note the use of >= and >.

   Will let Twisted choose a default reactor (potential performance degradation).
   """ % str(e))
            pass

    if sys.platform in ['win32']:
        try:
            from twisted.application.reactors import installReactor
            installReactor("iocp")
        except Exception as e:
            print("""
   WARNING: Running on Windows, but cannot use IOCP Twisted reactor.

    => %s

   Will let Twisted choose a default reactor (potential performance degradation).
   """ % str(e))

    if sys.platform.startswith('linux'):
        try:
            from twisted.internet import epollreactor
            epollreactor.install()
        except Exception as e:
            print("""
   WARNING: Running on Linux, but cannot use Epoll Twisted reactor.

    => %s

   Will let Twisted choose a default reactor (potential performance degradation).
   """ % str(e))
示例#6
0
 def opt_reactor(self, shortName):
     """
     Which reactor to use (see --help-reactors for a list of possibilities)
     """
     # Actually actually actually install the reactor right at this very
     # moment, before any other code (for example, a sub-command plugin)
     # runs and accidentally imports and installs the default reactor.
     #
     # This could probably be improved somehow.
     installReactor(shortName)
示例#7
0
 def opt_reactor(self, shortName):
     """
     Which reactor to use (see --help-reactors for a list of possibilities)
     """
     # Actually actually actually install the reactor right at this very
     # moment, before any other code (for example, a sub-command plugin)
     # runs and accidentally imports and installs the default reactor.
     #
     # This could probably be improved somehow.
     installReactor(shortName)
示例#8
0
def install_optimal_reactor():
   """
   Try to install the optimal Twisted reactor for platform.
   """
   import sys

   if 'bsd' in sys.platform or sys.platform.startswith('darwin'):
      try:
         v = sys.version_info
         if v[0] == 1 or (v[0] == 2 and v[1] < 6) or (v[0] == 2 and v[1] == 6 and v[2] < 5):
            raise Exception("Python version too old (%s)" % sys.version)
         from twisted.internet import kqreactor
         kqreactor.install()
      except Exception as e:
         print("""
   WARNING: Running on BSD or Darwin, but cannot use kqueue Twisted reactor.

    => %s

   To use the kqueue Twisted reactor, you will need:

     1. Python >= 2.6.5 or PyPy > 1.8
     2. Twisted > 12.0

   Note the use of >= and >.

   Will let Twisted choose a default reactor (potential performance degradation).
   """ % str(e))
         pass

   if sys.platform in ['win32']:
      try:
         from twisted.application.reactors import installReactor
         installReactor("iocp")
      except Exception as e:
         print("""
   WARNING: Running on Windows, but cannot use IOCP Twisted reactor.

    => %s

   Will let Twisted choose a default reactor (potential performance degradation).
   """ % str(e))

   if sys.platform.startswith('linux'):
      try:
         from twisted.internet import epollreactor
         epollreactor.install()
      except Exception as e:
         print("""
   WARNING: Running on Linux, but cannot use Epoll Twisted reactor.

    => %s

   Will let Twisted choose a default reactor (potential performance degradation).
   """ % str(e))
def install_reactor(explicit_reactor=None, verbose=False, log=None, require_optimal_reactor=True):
    """
    Install Twisted reactor.

    :param explicit_reactor: If provided, install this reactor. Else, install
        the optimal reactor.
    :type explicit_reactor: obj

    :param verbose: If ``True``, log (at level "info") the reactor that is
        in place afterwards.
    :type verbose: bool

    :param log: Explicit logging to this txaio logger object.
    :type log: obj

    :param require_optimal_reactor: If ``True`` and the desired reactor could not be installed,
        raise ``ReactorAlreadyInstalledError``, else fallback to another reactor.
    :type require_optimal_reactor: bool

    :returns: The Twisted reactor in place (`twisted.internet.reactor`).
    """
    if not log:
        log = txaio.make_logger()

    if explicit_reactor:
        # install explicitly given reactor
        #
        from twisted.application.reactors import installReactor
        if verbose:
            log.info('Trying to install explicitly specified Twisted reactor "{reactor}" ..', reactor=explicit_reactor)
        try:
            installReactor(explicit_reactor)
        except:
            log.failure('Could not install Twisted reactor {reactor}\n{log_failure.value}',
                        reactor=explicit_reactor)
            sys.exit(1)
    else:
        # automatically choose optimal reactor
        #
        if verbose:
            log.info('Automatically choosing optimal Twisted reactor ..')
        install_optimal_reactor(require_optimal_reactor)

    # now the reactor is installed, import it
    from twisted.internet import reactor
    txaio.config.loop = reactor

    if verbose:
        from twisted.python.reflect import qual
        log.info('Running on Twisted reactor {reactor}', reactor=qual(reactor.__class__))

    return reactor
示例#10
0
def main():
    """
    Try to install the reactor named C{qt}.  Expect it to not work.  Print
    diagnostics to stdout if something goes wrong, print nothing otherwise.
    """
    sys.meta_path.insert(0, QTNotImporter())
    try:
        reactors.installReactor('qt')
    except reactors.NoSuchReactor, e:
        if e.args != ('qt',):
            print 'Wrong arguments to NoSuchReactor:', e.args
        else:
            # Do nothing to indicate success.
            pass
示例#11
0
def main():
    """
    Try to install the reactor named C{qt}.  Expect it to not work.  Print
    diagnostics to stdout if something goes wrong, print nothing otherwise.
    """
    sys.meta_path.insert(0, QTNotImporter())
    try:
        reactors.installReactor('qt')
    except reactors.NoSuchReactor, e:
        if e.args != ('qt', ):
            print 'Wrong arguments to NoSuchReactor:', e.args
        else:
            # Do nothing to indicate success.
            pass
示例#12
0
 def test_installReactor(self):
     """
     Test that the L{reactors.installReactor} function correctly installs
     the specified reactor.
     """
     installed = []
     def install():
         installed.append(True)
     name = 'fakereactortest'
     package = __name__
     description = 'description'
     self.pluginResults = [FakeReactor(install, name, package, description)]
     reactors.installReactor(name)
     self.assertEqual(installed, [True])
示例#13
0
 def test_installReactor(self):
     """
     Test that the L{reactors.installReactor} function correctly installs
     the specified reactor.
     """
     installed = []
     def install():
         installed.append(True)
     name = 'fakereactortest'
     package = __name__
     description = 'description'
     self.pluginResults = [FakeReactor(install, name, package, description)]
     reactors.installReactor(name)
     self.assertEqual(installed, [True])
示例#14
0
def install_reactor(_reactor = None, verbose = False):
   """
   Install Twisted reactor. This is used from CLI.
   """
   import sys

   if _reactor:
      ## install explicitly given reactor
      ##
      from twisted.application.reactors import installReactor
      print "Trying to install explicitly specified Twisted reactor '%s'" % _reactor
      try:
         installReactor(_reactor)
      except Exception, e:
         print "Could not install Twisted reactor %s%s" % (_reactor, ' ["%s"]' % e if verbose else '')
         sys.exit(1)
示例#15
0
def install_reactor(_reactor = None, verbose = False):
   """
   Install Twisted reactor. This is used from CLI.
   """
   import sys

   if _reactor:
      ## install explicitly given reactor
      ##
      from twisted.application.reactors import installReactor
      print "Trying to install explicitly specified Twisted reactor '%s'" % _reactor
      try:
         installReactor(_reactor)
      except Exception, e:
         print "Could not install Twisted reactor %s%s" % (_reactor, ' ["%s"]' % e if verbose else '')
         sys.exit(1)
示例#16
0
 def test_installReactorMultiplePlugins(self):
     """
     Test that the L{reactors.installReactor} function correctly installs
     the specified reactor when there are multiple reactor plugins.
     """
     installed = []
     def install():
         installed.append(True)
     name = 'fakereactortest'
     package = __name__
     description = 'description'
     fakeReactor = FakeReactor(install, name, package, description)
     otherReactor = FakeReactor(lambda: None,
                                "otherreactor", package, description)
     self.pluginResults = [otherReactor, fakeReactor]
     reactors.installReactor(name)
     self.assertEqual(installed, [True])
 def test_installReactorMultiplePlugins(self):
     """
     Test that the L{reactors.installReactor} function correctly installs
     the specified reactor when there are multiple reactor plugins.
     """
     installed = []
     def install():
         installed.append(True)
     name = 'fakereactortest'
     package = __name__
     description = 'description'
     fakeReactor = FakeReactor(install, name, package, description)
     otherReactor = FakeReactor(lambda: None,
                                "otherreactor", package, description)
     self.pluginResults = [otherReactor, fakeReactor]
     reactors.installReactor(name)
     self.assertEqual(installed, [True])
示例#18
0
def install_reactor(explicit_reactor=None, verbose=False):
    """
    Install Twisted reactor.

    :param explicit_reactor: If provided, install this reactor. Else, install
        the optimal reactor.
    :type explicit_reactor: obj
    :param verbose: If ``True``, print what happens.
    :type verbose: bool
    """
    import sys
    import txaio
    txaio.use_twisted()  # just to be sure...

    log = make_logger()

    if explicit_reactor:
        # install explicitly given reactor
        ##
        from twisted.application.reactors import installReactor
        log.info(
            "Trying to install explicitly specified Twisted reactor '{reactor}'",
            reactor=explicit_reactor)
        try:
            installReactor(explicit_reactor)
        except:
            log.failure(
                "Could not install Twisted reactor {reactor}\n{log_failure.value}",
                reactor=explicit_reactor)
            sys.exit(1)
    else:
        # automatically choose optimal reactor
        ##
        log.debug("Automatically choosing optimal Twisted reactor")
        install_optimal_reactor(verbose)

    # now the reactor is installed, import it
    from twisted.internet import reactor
    txaio.config.loop = reactor

    if verbose:
        from twisted.python.reflect import qual
        log.debug("Running Twisted reactor {reactor}",
                  reactor=qual(reactor.__class__))

    return reactor
def install_reactor(explicit_reactor=None, verbose=False):
    """
    Install Twisted reactor.

    :param explicit_reactor: If provided, install this reactor. Else, install
        the optimal reactor.
    :type explicit_reactor: obj
    :param verbose: If ``True``, print what happens.
    :type verbose: bool
    """
    import sys
    import txaio
    txaio.use_twisted()  # just to be sure...

    log = make_logger()

    if explicit_reactor:
        # install explicitly given reactor
        ##
        from twisted.application.reactors import installReactor
        log.info("Trying to install explicitly specified Twisted reactor '{reactor}'", reactor=explicit_reactor)
        try:
            installReactor(explicit_reactor)
        except:
            log.failure("Could not install Twisted reactor {reactor}\n{log_failure.value}",
                        reactor=explicit_reactor)
            sys.exit(1)
    else:
        # automatically choose optimal reactor
        ##
        log.debug("Automatically choosing optimal Twisted reactor")
        install_optimal_reactor(verbose)

    # now the reactor is installed, import it
    from twisted.internet import reactor
    txaio.config.loop = reactor

    if verbose:
        from twisted.python.reflect import qual
        log.debug("Running Twisted reactor {reactor}", reactor=qual(reactor.__class__))

    return reactor
示例#20
0
def install_reactor(explicitReactor=None, verbose=False):
    """
    Install Twisted reactor.

    :param explicitReactor: If provided, install this reactor. Else, install optimal reactor.
    :type explicitReactor: obj
    :param verbose: If ``True``, print what happens.
    :type verbose: bool
    """
    import sys
    import txaio
    txaio.use_twisted()  # just to be sure...

    if explicitReactor:
        # install explicitly given reactor
        ##
        from twisted.application.reactors import installReactor
        print("Trying to install explicitly specified Twisted reactor '%s'" %
              explicitReactor)
        try:
            installReactor(explicitReactor)
        except Exception as e:
            print("Could not install Twisted reactor %s%s" %
                  (explicitReactor, ' ["%s"]' % e if verbose else ''))
            sys.exit(1)
    else:
        # automatically choose optimal reactor
        ##
        if verbose:
            print("Automatically choosing optimal Twisted reactor")
        install_optimal_reactor(verbose)

    # now the reactor is installed, import it
    from twisted.internet import reactor
    txaio.config.loop = reactor

    if verbose:
        from twisted.python.reflect import qual
        print("Running Twisted reactor %s" % qual(reactor.__class__))

    return reactor
示例#21
0
文件: app.py 项目: antong/twisted
 def opt_reactor(self, shortName):
     """
     Which reactor to use (see --help-reactors for a list of possibilities)
     """
     # Actually actually actually install the reactor right at this very
     # moment, before any other code (for example, a sub-command plugin)
     # runs and accidentally imports and installs the default reactor.
     #
     # This could probably be improved somehow.
     try:
         installReactor(shortName)
     except NoSuchReactor:
         msg = ("The specified reactor does not exist: '%s'.\n"
                "See the list of available reactors with "
                "--help-reactors" % (shortName,))
         raise usage.UsageError(msg)
     except Exception, e:
         msg = ("The specified reactor cannot be used, failed with error: "
                "%s.\nSee the list of available reactors with "
                "--help-reactors" % (e,))
         raise usage.UsageError(msg)
示例#22
0
def install_reactor(explicitReactor=None, verbose=False):
    """
    Install Twisted reactor.

    :param explicitReactor: If provided, install this reactor. Else, install optimal reactor.
    :type explicitReactor: obj
    :param verbose: If ``True``, print what happens.
    :type verbose: bool
    """
    import sys
    import txaio
    txaio.use_twisted()  # just to be sure...

    if explicitReactor:
        # install explicitly given reactor
        ##
        from twisted.application.reactors import installReactor
        print("Trying to install explicitly specified Twisted reactor '%s'" % explicitReactor)
        try:
            installReactor(explicitReactor)
        except Exception as e:
            print("Could not install Twisted reactor %s%s" % (explicitReactor, ' ["%s"]' % e if verbose else ''))
            sys.exit(1)
    else:
        # automatically choose optimal reactor
        ##
        if verbose:
            print("Automatically choosing optimal Twisted reactor")
        install_optimal_reactor(verbose)

    # now the reactor is installed, import it
    from twisted.internet import reactor
    txaio.config.loop = reactor

    if verbose:
        from twisted.python.reflect import qual
        print("Running Twisted reactor %s" % qual(reactor.__class__))

    return reactor
示例#23
0
 def test_installReactorReturnsReactor(self):
     """
     Test that the L{reactors.installReactor} function correctly returns
     the installed reactor.
     """
     reactor = object()
     def install():
         from twisted import internet
         self.patch(internet, 'reactor', reactor)
     name = 'fakereactortest'
     package = __name__
     description = 'description'
     self.pluginResults = [FakeReactor(install, name, package, description)]
     installed = reactors.installReactor(name)
     self.assertIs(installed, reactor)
 def test_installReactorReturnsReactor(self):
     """
     Test that the L{reactors.installReactor} function correctly returns
     the installed reactor.
     """
     reactor = object()
     def install():
         from twisted import internet
         self.patch(internet, 'reactor', reactor)
     name = 'fakereactortest'
     package = __name__
     description = 'description'
     self.pluginResults = [FakeReactor(install, name, package, description)]
     installed = reactors.installReactor(name)
     self.assertIdentical(installed, reactor)
# works:
# from PySide2 import QtCore, QtWidgets

# "works", but segfaults on exit:
from PySide6 import QtCore, QtWidgets

import sys

app = QtWidgets.QApplication(sys.argv)

from twisted.application import reactors

reactors.installReactor('pyside2')

from twisted.internet import reactor
from twisted.internet.task import LoopingCall

mywindow = QtWidgets.QWidget()
mywindow.resize(600, 400)
mywindow.setWindowTitle('Hello, World!')

mylabel = QtWidgets.QLabel(mywindow)
mylabel.setGeometry(QtCore.QRect(200, 200, 200, 200))

count = 0


def set_label():
    global count
    global mylabel
    count += 1
            app = MarketApplicationRABO(sys.argv)
    elif args.bank == "moneyou":
        if args.scenario == "bank":
            app = MarketAppSceneBankMONEYOU(sys.argv)
        else:
            app = MarketApplicationMONEYOU(sys.argv)
    else:
        raise SystemExit("Unknown bank")

    if start_tftp_server:
        tftp_server = tftp_server.Server()
        tftp_server.set_logging(os.getcwd() + '/logging/', 'INFO')
        tftp_server.start()

    from twisted.application import reactors
    reactors.installReactor('qt5')

    from twisted.internet import reactor

    reactor.callWhenRunning(app.start_dispersy)
    app.initialize()
    reactor.runReturn()

    if not args.headless:
        from market.controllers.main_window_controller import MainWindowController

        form = MainWindowController(app=app)
        form.show()

    app.exec_()
示例#27
0
import sys, random, time, pprint

if "bsd" in sys.platform or sys.platform.startswith("darwin"):
    from twisted.internet import kqreactor

    kqreactor.install()
elif sys.platform in ["win32"]:
    from twisted.application.reactors import installReactor

    installReactor("iocp")
elif sys.platform.startswith("linux"):
    from twisted.internet import epollreactor

    epollreactor.install()

from twisted.internet import reactor

from twisted.python import log
from twisted.internet.defer import Deferred, DeferredList, gatherResults, returnValue, inlineCallbacks

from twisted.internet.threads import deferToThread


def newid():
    return "".join(
        [random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") for i in xrange(16)]
    )


if sys.platform.startswith("win"):
    rtime = time.clock
示例#28
0
from __future__ import print_function
__author__ = 'ght'

import q

from twisted.application import reactors

reactors.installReactor('kqueue')

from twisted.python import log

import sys

log.startLogging(sys.stdout)

# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

from twisted.internet import reactor, protocol


class Echo(protocol.Protocol):
    """This is just about the simplest possible protocol"""
    def dataReceived(self, data):
        q('server: ', data)
        "As soon as any data is received, write it back."
        self.transport.write(data)


def main():
    """This runs the protocol on port 8000"""
示例#29
0
    config = ConfigParser(args.configfile)
except ConfigurationError as e:
    parser.error(e)

# emulate twisted configuration:
twisted_config = DefaultDict()
twisted_config['nodaemon'] = not (args.daemon or config.daemon or False)
twisted_config['no_save'] = True
twisted_config['originalname'] = 'openvpn2dns'
twisted_config['prefix'] = 'openvpn2dns'
twisted_config['rundir'] = '.'
if (args.drop or config.drop) is True:
    twisted_config['uid'] = args.user or config.user
    if not twisted_config['uid']:
        parser.error('Need user (and group) information to drop privileges')
    twisted_config['gid'] = args.group or config.group
    if not twisted_config['gid']:
        parser.error('Need group information to drop privileges')
if (args.log or config.log) == 'syslog':
    twisted_config['syslog'] = True
elif args.log or config.log:
    twisted_config['log'] = args.log or config.log
twisted_config['pidfile'] = args.pidfile or config.pidfile


if args.reactor or config.reactor:
    installReactor(args.reactor or config.reactor)

# run appliation:
OpenVpn2DnsApplication(config, twisted_config).run()
示例#30
0
import sys

from twisted.application import reactors
reactors.installReactor('qt4')

from twisted.internet import reactor, task
from twisted.python import log
log.startLogging(sys.stdout)
 
def testReactor():
    print 'tick...'

def doit():
    task.LoopingCall(testReactor).start(1.0)
    reactor.callLater(15.0,reactor.stop)
    
reactor.callWhenRunning(doit)
log.msg('calling reactor.run()')
reactor.run()
log.msg('fell off the bottom?...')

#sys.exit(app.exec_())

# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for lots of functionality provided by L{twisted.internet}.
"""


import os
import sys
import time

from twisted.application import reactors

reactors.installReactor("qt4")

from twisted.python.compat import _PY3
from twisted.trial import unittest
from twisted.internet import reactor, protocol, error, abstract, defer
from twisted.internet import interfaces, base

try:
    from twisted.internet import ssl
except ImportError:
    ssl = None
if ssl and not ssl.supported:
    ssl = None

from twisted.internet.defer import Deferred, maybeDeferred
from twisted.python import runtime
示例#32
0
__author__ = 'ght'


from twisted.application import reactors

reactors.installReactor('kqueue')

# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Test running processes.
"""

import gzip
import os
import sys
import signal
import StringIO
import errno
import gc
import stat
import operator
try:
    import fcntl
except ImportError:
    fcntl = process = None
else:
    from twisted.internet import process

示例#33
0
   To use the kqueue Twisted reactor, you will need:

     1. Python >= 2.6.5 or PyPy > 1.8
     2. Twisted > 12.0

   Note the use of >= and >.

   Will let Twisted choose a default reactor (potential performance degradation).
   """ % str(e)
            pass

    if sys.platform in ['win32']:
        try:
            from twisted.application.reactors import installReactor
            installReactor("iocp")
        except Exception, e:
            print """
   WARNING: Running on Windows, but cannot use IOCP Twisted reactor.

    => %s

   Will let Twisted choose a default reactor (potential performance degradation).
   """ % str(e)

    if sys.platform.startswith('linux'):
        try:
            from twisted.internet import epollreactor
            epollreactor.install()
        except Exception, e:
            print """
示例#34
0
from __future__ import print_function
__author__ = 'ght'

from twisted.application import reactors

reactors.installReactor('pyqt4')

from twisted.internet.task import LoopingCall
from twisted.internet import reactor

from twisted.python import log

import sys
#log.startLogging(sys.stdout)

trialpath = '/usr/local/bin/trial'
trial = open(trialpath, 'r').read()


def aliveness():
    print('tick')


lc = LoopingCall(aliveness)


def shutdown():
    lc.stop()


lc = LoopingCall(aliveness)
示例#35
0
def main(args=None, locals_=None, banner=None):
    translations.init()

    # TODO: maybe support displays other than raw_display?
    config, options, exec_args = bpargs.parse(args, ('Urwid options', None, [
        Option('--twisted',
               '-T',
               action='store_true',
               help=_('Run twisted reactor.')),
        Option('--reactor',
               '-r',
               help=_('Select specific reactor (see --help-reactors). '
                      'Implies --twisted.')),
        Option('--help-reactors',
               action='store_true',
               help=_('List available reactors for -r.')),
        Option('--plugin',
               '-p',
               help=_('twistd plugin to run (use twistd for a list). '
                      'Use "--" to pass further options to the plugin.')),
        Option('--server',
               '-s',
               type='int',
               help=_('Port to run an eval server on (forces Twisted).')),
    ]))

    if options.help_reactors:
        try:
            from twisted.application import reactors
            # Stolen from twisted.application.app (twistd).
            for r in reactors.getReactorTypes():
                print('    %-4s\t%s' % (r.shortName, r.description))
        except ImportError:
            sys.stderr.write('No reactors are available. Please install '
                             'twisted for reactor support.\n')
        return

    palette = [(name, COLORMAP[color.lower()], 'default',
                'bold' if color.isupper() else 'default')
               for name, color in config.color_scheme.items()]
    palette.extend([('bold ' + name, color + ',bold', background, monochrome)
                    for name, color, background, monochrome in palette])

    if options.server or options.plugin:
        options.twisted = True

    if options.reactor:
        try:
            from twisted.application import reactors
        except ImportError:
            sys.stderr.write('No reactors are available. Please install '
                             'twisted for reactor support.\n')
            return
        try:
            # XXX why does this not just return the reactor it installed?
            reactor = reactors.installReactor(options.reactor)
            if reactor is None:
                from twisted.internet import reactor
        except reactors.NoSuchReactor:
            sys.stderr.write('Reactor %s does not exist\n' %
                             (options.reactor, ))
            return
        event_loop = TwistedEventLoop(reactor)
    elif options.twisted:
        try:
            from twisted.internet import reactor
        except ImportError:
            sys.stderr.write('No reactors are available. Please install '
                             'twisted for reactor support.\n')
            return
        event_loop = TwistedEventLoop(reactor)
    else:
        # None, not urwid.SelectEventLoop(), to work with
        # screens that do not support external event loops.
        event_loop = None
    # TODO: there is also a glib event loop. Do we want that one?

    # __main__ construction from bpython.cli
    if locals_ is None:
        main_mod = sys.modules['__main__'] = ModuleType('__main__')
        locals_ = main_mod.__dict__

    if options.plugin:
        try:
            from twisted import plugin
            from twisted.application import service
        except ImportError:
            sys.stderr.write(
                'No twisted plugins are available. Please install '
                'twisted for twisted plugin support.\n')
            return

        for plug in plugin.getPlugins(service.IServiceMaker):
            if plug.tapname == options.plugin:
                break
        else:
            sys.stderr.write('Plugin %s does not exist\n' % (options.plugin, ))
            return
        plugopts = plug.options()
        plugopts.parseOptions(exec_args)
        serv = plug.makeService(plugopts)
        locals_['service'] = serv
        reactor.callWhenRunning(serv.startService)
        exec_args = []
    interpreter = repl.Interpreter(locals_, locale.getpreferredencoding())

    # This nabs sys.stdin/out via urwid.MainLoop
    myrepl = URWIDRepl(event_loop, palette, interpreter, config)

    if options.server:
        factory = EvalFactory(myrepl)
        reactor.listenTCP(options.server, factory, interface='127.0.0.1')

    if options.reactor:
        # Twisted sets a sigInt handler that stops the reactor unless
        # it sees a different custom signal handler.
        def sigint(*args):
            reactor.callFromThread(myrepl.keyboard_interrupt)

        signal.signal(signal.SIGINT, sigint)

    # Save stdin, stdout and stderr for later restoration
    orig_stdin = sys.stdin
    orig_stdout = sys.stdout
    orig_stderr = sys.stderr

    # urwid's screen start() and stop() calls currently hit sys.stdin
    # directly (via RealTerminal.tty_signal_keys), so start the screen
    # before swapping sys.std*, and swap them back before restoring
    # the screen. This also avoids crashes if our redirected sys.std*
    # are called before we get around to starting the mainloop
    # (urwid raises an exception if we try to draw to the screen
    # before starting it).
    def run_with_screen_before_mainloop():
        try:
            # Currently we just set this to None because I do not
            # expect code hitting stdin to work. For example: exit()
            # (not sys.exit, site.py's exit) tries to close sys.stdin,
            # which breaks urwid's shutdown. bpython.cli sets this to
            # a fake object that reads input through curses and
            # returns it. When using twisted I do not think we can do
            # that because sys.stdin.read and friends block, and we
            # cannot re-enter the reactor. If using urwid's own
            # mainloop we *might* be able to do something similar and
            # re-enter its mainloop.
            sys.stdin = None  #FakeStdin(myrepl)
            sys.stdout = myrepl
            sys.stderr = myrepl

            myrepl.main_loop.set_alarm_in(0, start)

            while True:
                try:
                    myrepl.main_loop.run()
                except KeyboardInterrupt:
                    # HACK: if we run under a twisted mainloop this should
                    # never happen: we have a SIGINT handler set.
                    # If we use the urwid select-based loop we just restart
                    # that loop if interrupted, instead of trying to cook
                    # up an equivalent to reactor.callFromThread (which
                    # is what our Twisted sigint handler does)
                    myrepl.main_loop.set_alarm_in(
                        0, lambda *args: myrepl.keyboard_interrupt())
                    continue
                break

        finally:
            sys.stdin = orig_stdin
            sys.stderr = orig_stderr
            sys.stdout = orig_stdout

    # This needs more thought. What needs to happen inside the mainloop?
    def start(main_loop, user_data):
        if exec_args:
            bpargs.exec_code(interpreter, exec_args)
            if not options.interactive:
                raise urwid.ExitMainLoop()
        if not exec_args:
            sys.path.insert(0, '')
            # this is CLIRepl.startup inlined.
            filename = os.environ.get('PYTHONSTARTUP')
            if filename and os.path.isfile(filename):
                with open(filename, 'r') as f:
                    if py3:
                        interpreter.runsource(f.read(), filename, 'exec')
                    else:
                        interpreter.runsource(f.read(),
                                              filename,
                                              'exec',
                                              encode=False)

        if banner is not None:
            repl.write(banner)
            repl.write('\n')
        myrepl.start()

        # This bypasses main_loop.set_alarm_in because we must *not*
        # hit the draw_screen call (it's unnecessary and slow).
        def run_find_coroutine():
            if find_coroutine():
                main_loop.event_loop.alarm(0, run_find_coroutine)

        run_find_coroutine()

    myrepl.main_loop.screen.run_wrapper(run_with_screen_before_mainloop)

    if config.flush_output and not options.quiet:
        sys.stdout.write(myrepl.getstdout())
    if hasattr(sys.stdout, "flush"):
        sys.stdout.flush()
    return repl.extract_exit_value(myrepl.exit_value)
def main(args=None, locals_=None, banner=None):
    translations.init()

    # TODO: maybe support displays other than raw_display?
    config, options, exec_args = bpargs.parse(args, (
            'Urwid options', None, [
                Option('--twisted', '-T', action='store_true',
                       help=_('Run twisted reactor.')),
                Option('--reactor', '-r',
                       help=_('Select specific reactor (see --help-reactors). '
                       'Implies --twisted.')),
                Option('--help-reactors', action='store_true',
                       help=_('List available reactors for -r.')),
                Option('--plugin', '-p',
                       help=_('twistd plugin to run (use twistd for a list). '
                       'Use "--" to pass further options to the plugin.')),
                Option('--server', '-s', type='int',
                       help=_('Port to run an eval server on (forces Twisted).')),
                ]))

    if options.help_reactors:
        try:
            from twisted.application import reactors
            # Stolen from twisted.application.app (twistd).
            for r in reactors.getReactorTypes():
                print('    %-4s\t%s' % (r.shortName, r.description))
        except ImportError:
            sys.stderr.write('No reactors are available. Please install '
                'twisted for reactor support.\n')
        return

    palette = [
        (name, COLORMAP[color.lower()], 'default',
         'bold' if color.isupper() else 'default')
        for name, color in iteritems(config.color_scheme)]
    palette.extend([
            ('bold ' + name, color + ',bold', background, monochrome)
            for name, color, background, monochrome in palette])

    if options.server or options.plugin:
        options.twisted = True

    if options.reactor:
        try:
            from twisted.application import reactors
        except ImportError:
            sys.stderr.write('No reactors are available. Please install '
                'twisted for reactor support.\n')
            return
        try:
            # XXX why does this not just return the reactor it installed?
            reactor = reactors.installReactor(options.reactor)
            if reactor is None:
                from twisted.internet import reactor
        except reactors.NoSuchReactor:
            sys.stderr.write('Reactor %s does not exist\n' % (
                    options.reactor,))
            return
        event_loop = TwistedEventLoop(reactor)
    elif options.twisted:
        try:
            from twisted.internet import reactor
        except ImportError:
            sys.stderr.write('No reactors are available. Please install '
                'twisted for reactor support.\n')
            return
        event_loop = TwistedEventLoop(reactor)
    else:
        # None, not urwid.SelectEventLoop(), to work with
        # screens that do not support external event loops.
        event_loop = None
    # TODO: there is also a glib event loop. Do we want that one?

    # __main__ construction from bpython.cli
    if locals_ is None:
        main_mod = sys.modules['__main__'] = ModuleType('__main__')
        locals_ = main_mod.__dict__

    if options.plugin:
        try:
            from twisted import plugin
            from twisted.application import service
        except ImportError:
            sys.stderr.write('No twisted plugins are available. Please install '
                'twisted for twisted plugin support.\n')
            return

        for plug in plugin.getPlugins(service.IServiceMaker):
            if plug.tapname == options.plugin:
                break
        else:
            sys.stderr.write('Plugin %s does not exist\n' % (options.plugin,))
            return
        plugopts = plug.options()
        plugopts.parseOptions(exec_args)
        serv = plug.makeService(plugopts)
        locals_['service'] = serv
        reactor.callWhenRunning(serv.startService)
        exec_args = []
    interpreter = repl.Interpreter(locals_, locale.getpreferredencoding())

    # This nabs sys.stdin/out via urwid.MainLoop
    myrepl = URWIDRepl(event_loop, palette, interpreter, config)

    if options.server:
        factory = EvalFactory(myrepl)
        reactor.listenTCP(options.server, factory, interface='127.0.0.1')

    if options.reactor:
        # Twisted sets a sigInt handler that stops the reactor unless
        # it sees a different custom signal handler.
        def sigint(*args):
            reactor.callFromThread(myrepl.keyboard_interrupt)
        signal.signal(signal.SIGINT, sigint)

    # Save stdin, stdout and stderr for later restoration
    orig_stdin = sys.stdin
    orig_stdout = sys.stdout
    orig_stderr = sys.stderr
    # urwid's screen start() and stop() calls currently hit sys.stdin
    # directly (via RealTerminal.tty_signal_keys), so start the screen
    # before swapping sys.std*, and swap them back before restoring
    # the screen. This also avoids crashes if our redirected sys.std*
    # are called before we get around to starting the mainloop
    # (urwid raises an exception if we try to draw to the screen
    # before starting it).
    def run_with_screen_before_mainloop():
        try:
            # Currently we just set this to None because I do not
            # expect code hitting stdin to work. For example: exit()
            # (not sys.exit, site.py's exit) tries to close sys.stdin,
            # which breaks urwid's shutdown. bpython.cli sets this to
            # a fake object that reads input through curses and
            # returns it. When using twisted I do not think we can do
            # that because sys.stdin.read and friends block, and we
            # cannot re-enter the reactor. If using urwid's own
            # mainloop we *might* be able to do something similar and
            # re-enter its mainloop.
            sys.stdin = None #FakeStdin(myrepl)
            sys.stdout = myrepl
            sys.stderr = myrepl

            myrepl.main_loop.set_alarm_in(0, start)

            while True:
                try:
                    myrepl.main_loop.run()
                except KeyboardInterrupt:
                    # HACK: if we run under a twisted mainloop this should
                    # never happen: we have a SIGINT handler set.
                    # If we use the urwid select-based loop we just restart
                    # that loop if interrupted, instead of trying to cook
                    # up an equivalent to reactor.callFromThread (which
                    # is what our Twisted sigint handler does)
                    myrepl.main_loop.set_alarm_in(
                        0, lambda *args: myrepl.keyboard_interrupt())
                    continue
                break

        finally:
            sys.stdin = orig_stdin
            sys.stderr = orig_stderr
            sys.stdout = orig_stdout

    # This needs more thought. What needs to happen inside the mainloop?
    def start(main_loop, user_data):
        if exec_args:
            bpargs.exec_code(interpreter, exec_args)
            if not options.interactive:
                raise urwid.ExitMainLoop()
        if not exec_args:
            sys.path.insert(0, '')
            # this is CLIRepl.startup inlined.
            filename = os.environ.get('PYTHONSTARTUP')
            if filename and os.path.isfile(filename):
                with open(filename, 'r') as f:
                    if py3:
                        interpreter.runsource(f.read(), filename, 'exec')
                    else:
                        interpreter.runsource(f.read(), filename, 'exec',
                                              encode=False)

        if banner is not None:
            myrepl.write(banner)
            myrepl.write('\n')
        myrepl.start()

        # This bypasses main_loop.set_alarm_in because we must *not*
        # hit the draw_screen call (it's unnecessary and slow).
        def run_find_coroutine():
            if find_coroutine():
                main_loop.event_loop.alarm(0, run_find_coroutine)

        run_find_coroutine()

    myrepl.main_loop.screen.run_wrapper(run_with_screen_before_mainloop)

    if config.flush_output and not options.quiet:
        sys.stdout.write(myrepl.getstdout())
    if hasattr(sys.stdout, "flush"):
        sys.stdout.flush()
    return repl.extract_exit_value(myrepl.exit_value)
示例#37
0
def main(args=None, locals_=None, banner=None):
    translations.init()

    def options_callback(group):
        group.add_argument(
            "--twisted",
            "-T",
            action="store_true",
            help=_("Run twisted reactor."),
        )
        group.add_argument(
            "--reactor",
            "-r",
            help=_("Select specific reactor (see --help-reactors). "
                   "Implies --twisted."),
        )
        group.add_argument(
            "--help-reactors",
            action="store_true",
            help=_("List available reactors for -r."),
        )
        group.add_argument(
            "--plugin",
            "-p",
            help=_("twistd plugin to run (use twistd for a list). "
                   'Use "--" to pass further options to the plugin.'),
        )
        group.add_argument(
            "--server",
            "-s",
            type=int,
            help=_("Port to run an eval server on (forces Twisted)."),
        )

    # TODO: maybe support displays other than raw_display?
    config, options, exec_args = bpargs.parse(
        args,
        (
            "Urwid options",
            None,
            options_callback,
        ),
    )

    if options.help_reactors:
        try:
            from twisted.application import reactors

            # Stolen from twisted.application.app (twistd).
            for r in reactors.getReactorTypes():
                print(f"    {r.shortName:<4}\t{r.description}")
        except ImportError:
            sys.stderr.write("No reactors are available. Please install "
                             "twisted for reactor support.\n")
        return

    palette = [(
        name,
        COLORMAP[color.lower()],
        "default",
        "bold" if color.isupper() else "default",
    ) for name, color in config.color_scheme.items()]
    palette.extend([("bold " + name, color + ",bold", background, monochrome)
                    for name, color, background, monochrome in palette])

    if options.server or options.plugin:
        options.twisted = True

    if options.reactor:
        try:
            from twisted.application import reactors
        except ImportError:
            sys.stderr.write("No reactors are available. Please install "
                             "twisted for reactor support.\n")
            return
        try:
            # XXX why does this not just return the reactor it installed?
            reactor = reactors.installReactor(options.reactor)
            if reactor is None:
                from twisted.internet import reactor
        except reactors.NoSuchReactor:
            sys.stderr.write(f"Reactor {options.reactor} does not exist\n")
            return
        event_loop = TwistedEventLoop(reactor)
    elif options.twisted:
        try:
            from twisted.internet import reactor
        except ImportError:
            sys.stderr.write("No reactors are available. Please install "
                             "twisted for reactor support.\n")
            return
        event_loop = TwistedEventLoop(reactor)
    else:
        # None, not urwid.SelectEventLoop(), to work with
        # screens that do not support external event loops.
        event_loop = None
    # TODO: there is also a glib event loop. Do we want that one?

    extend_locals = {}
    if options.plugin:
        try:
            from twisted import plugin
            from twisted.application import service
        except ImportError:
            sys.stderr.write(
                "No twisted plugins are available. Please install "
                "twisted for twisted plugin support.\n")
            return

        for plug in plugin.getPlugins(service.IServiceMaker):
            if plug.tapname == options.plugin:
                break
        else:
            sys.stderr.write(f"Plugin {options.plugin} does not exist\n")
            return
        plugopts = plug.options()
        plugopts.parseOptions(exec_args)
        serv = plug.makeService(plugopts)
        extend_locals["service"] = serv
        reactor.callWhenRunning(serv.startService)
        exec_args = []
    interpreter = repl.Interpreter(locals_, locale.getpreferredencoding())
    # TODO: replace with something less hack-ish
    interpreter.locals.update(extend_locals)

    # This nabs sys.stdin/out via urwid.MainLoop
    myrepl = URWIDRepl(event_loop, palette, interpreter, config)

    if options.server:
        factory = EvalFactory(myrepl)
        reactor.listenTCP(options.server, factory, interface="127.0.0.1")

    if options.reactor:
        # Twisted sets a sigInt handler that stops the reactor unless
        # it sees a different custom signal handler.
        def sigint(*args):
            reactor.callFromThread(myrepl.keyboard_interrupt)

        signal.signal(signal.SIGINT, sigint)

    # Save stdin, stdout and stderr for later restoration
    orig_stdin = sys.stdin
    orig_stdout = sys.stdout
    orig_stderr = sys.stderr

    # urwid's screen start() and stop() calls currently hit sys.stdin
    # directly (via RealTerminal.tty_signal_keys), so start the screen
    # before swapping sys.std*, and swap them back before restoring
    # the screen. This also avoids crashes if our redirected sys.std*
    # are called before we get around to starting the mainloop
    # (urwid raises an exception if we try to draw to the screen
    # before starting it).

    def run_with_screen_before_mainloop():
        try:
            # Currently we just set this to None because I do not
            # expect code hitting stdin to work. For example: exit()
            # (not sys.exit, site.py's exit) tries to close sys.stdin,
            # which breaks urwid's shutdown. bpython.cli sets this to
            # a fake object that reads input through curses and
            # returns it. When using twisted I do not think we can do
            # that because sys.stdin.read and friends block, and we
            # cannot re-enter the reactor. If using urwid's own
            # mainloop we *might* be able to do something similar and
            # re-enter its mainloop.
            sys.stdin = None  # FakeStdin(myrepl)
            sys.stdout = myrepl
            sys.stderr = myrepl

            myrepl.main_loop.set_alarm_in(0, start)

            while True:
                try:
                    myrepl.main_loop.run()
                except KeyboardInterrupt:
                    # HACK: if we run under a twisted mainloop this should
                    # never happen: we have a SIGINT handler set.
                    # If we use the urwid select-based loop we just restart
                    # that loop if interrupted, instead of trying to cook
                    # up an equivalent to reactor.callFromThread (which
                    # is what our Twisted sigint handler does)
                    myrepl.main_loop.set_alarm_in(
                        0, lambda *args: myrepl.keyboard_interrupt())
                    continue
                break

        finally:
            sys.stdin = orig_stdin
            sys.stderr = orig_stderr
            sys.stdout = orig_stdout

    # This needs more thought. What needs to happen inside the mainloop?
    def start(main_loop, user_data):
        if exec_args:
            bpargs.exec_code(interpreter, exec_args)
            if not options.interactive:
                raise urwid.ExitMainLoop()
        if not exec_args:
            sys.path.insert(0, "")
            # this is CLIRepl.startup inlined.
            filename = os.environ.get("PYTHONSTARTUP")
            if filename and os.path.isfile(filename):
                with open(filename) as f:
                    interpreter.runsource(f.read(), filename, "exec")

        if banner is not None:
            myrepl.write(banner)
            myrepl.write("\n")

        # XXX these deprecation warnings need to go at some point
        myrepl.write(
            _("WARNING: You are using `bpython-urwid`, the urwid backend for `bpython`. This backend has been deprecated in version 0.19 and might disappear in a future version."
              ))
        myrepl.write("\n")

        myrepl.start()

        # This bypasses main_loop.set_alarm_in because we must *not*
        # hit the draw_screen call (it's unnecessary and slow).
        def run_find_coroutine():
            if find_coroutine():
                main_loop.event_loop.alarm(0, run_find_coroutine)

        run_find_coroutine()

    myrepl.main_loop.screen.run_wrapper(run_with_screen_before_mainloop)

    if config.flush_output and not options.quiet:
        sys.stdout.write(myrepl.getstdout())
    if hasattr(sys.stdout, "flush"):
        sys.stdout.flush()
    return repl.extract_exit_value(myrepl.exit_value)
示例#38
0
 def install(self):
     installReactor(self.options.reactor)
     import twisted.internet.reactor
     return twisted.internet.reactor