本文整理汇总了Python中twisted.internet.reactor.addReader函数的典型用法代码示例。如果您正苦于以下问题:Python addReader函数的具体用法?Python addReader怎么用?Python addReader使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了addReader函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self):
class logObserver:
def __init__(self, con):
self.con = con
def emit(self, eventDict):
edm = eventDict['message']
if not edm:
if eventDict['isError'] and 'failure' in eventDict:
text = ((eventDict.get('why') or 'Unhandled Error')
+ '\n' + eventDict['failure'].getTraceback())
elif 'format' in eventDict:
text = eventDict['format'] % eventDict
else:
text = str(eventDict)
else:
text = ' '.join(map(reflect.safe_str, edm))
self.con.addLine(text)
stdscr = curses.initscr() # initialize curses
self.screen = Screen(stdscr) # create Screen object
log.addObserver(logObserver(self.screen).emit)
stdscr.refresh()
reactor.addReader(self.screen) # add screen object as a reader to the reactor
task.LoopingCall(self.screen.updateDisplay).start(.25)
开发者ID:jlew,项目名称:GrooveBot,代码行数:28,代码来源:ConsoleController.py
示例2: main
def main():
# parse options
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="Webserver port.",
metavar="<port>",
default=8080)
(options, args) = parser.parse_args()
twisted_client = Client()
#register Bionet callbacks
pybionet_register_callback_new_hab(cb_new_hab)
pybionet_register_callback_lost_hab(cb_lost_hab);
pybionet_register_callback_new_node(cb_new_node);
pybionet_register_callback_lost_node(cb_lost_node);
pybionet_register_callback_datapoint(cb_datapoint);
data = DataServer()
full = Datapoints()
root = Resource()
root.putChild('plot', File("plot.html"))
root.putChild('flot', File("flot"))
root.putChild('data', data)
root.putChild('full', full)
factory = Site(root)
reactor.listenTCP(options.port, factory)
reactor.addReader(twisted_client)
reactor.run()
开发者ID:SebKuzminsky,项目名称:hammerhead,代码行数:34,代码来源:bionetplot.py
示例3: configure
def configure(protocol, port, pipes, interface):
remove_all()
reactor.addSystemEventTrigger('after', 'shutdown', remove_all)
# gets default (outward-facing) network interface (e.g. deciding which of
# eth0, eth1, wlan0 is being used by the system to connect to the internet)
if interface == "auto":
interface = netifaces.gateways()['default'][netifaces.AF_INET][1]
else:
if interface not in netifaces.interfaces():
raise ValueError("Given interface does not exist.", interface)
add(protocol, port, interface)
manager = libnetfilter_queue.Manager()
def on_up(packet):
def accept():
manager.set_verdict(packet, libnetfilter_queue.NF_ACCEPT)
pipes.up.attempt(accept, packet.size)
def on_down(packet):
def accept():
manager.set_verdict(packet, libnetfilter_queue.NF_ACCEPT)
pipes.down.attempt(accept, packet.size)
manager.bind(UP_QUEUE, on_up)
manager.bind(DOWN_QUEUE, on_down)
reader = abstract.FileDescriptor()
reader.doRead = manager.process
reader.fileno = lambda: manager.fileno
reactor.addReader(reader)
开发者ID:kleopatra999,项目名称:packet-queue,代码行数:32,代码来源:nfqueue.py
示例4: main
def main():
parser = argparse.ArgumentParser(description="WaterRower monitor")
parser.add_argument("-p", "--port", dest="serial_port",
default="/dev/ttyUSB0")
parser.add_argument("-s", "--speed", dest="speed", default=1200)
parser.add_argument("-n", "--nodatalog", dest="record_datalog",
action='store_false')
parser.add_argument("-c", "--creds_filename",
help="Name of Google credentials file")
parser.add_argument("-g", "--name", help="Name of Google Spreadsheet")
parser.add_argument("-b", "--bucket",
help="Name of Google Cloud Storage bucket")
opts = parser.parse_args()
log.startLogging(file(
"collector-{}.log".format(
datetime.datetime.now().replace(microsecond=0).isoformat()),
'w'))
stdscr = curses.initscr()
session = InternetWaterRower(
record_datalog=opts.record_datalog,
creds_filename=opts.creds_filename,
spreadsheet_name=opts.name,
bucket_name=opts.bucket)
cons = InternetWaterRowerConsole(stdscr, session)
stdscr.refresh()
reactor.addReader(cons)
SerialPort(session, opts.serial_port, reactor, baudrate=opts.speed)
reactor.run()
cons.close()
开发者ID:nferch,项目名称:waterrower3,代码行数:35,代码来源:collector.py
示例5: __init__
def __init__(self, socket, callback=None, hosts=[]):
self.socket = socket
self.callback = callback
self.hosts = hosts
from twisted.internet import reactor
reactor.addReader(self)
开发者ID:cmek,项目名称:twistedping,代码行数:7,代码来源:icmpreader.py
示例6: afterDownload
def afterDownload(self, result, filename, deleteFile=False):
if os.path.getsize(filename) > 0:
print>>log, "[EPGImport] afterDownload", filename
if self.source.parser == 'epg.dat':
if twisted.python.runtime.platform.supportsThreads():
print>>log, "[EPGImport] Using twisted thread for DAT file"
threads.deferToThread(self.readEpgDatFile, filename, deleteFile).addCallback(lambda ignore: self.nextImport())
else:
self.readEpgDatFile(filename, deleteFile)
return
if filename.endswith('.gz'):
self.fd = gzip.open(filename, 'rb')
else:
self.fd = open(filename, 'rb')
if twisted.python.runtime.platform.supportsThreads():
print>>log, "[EPGImport] Using twisted thread!"
threads.deferToThread(self.doThreadRead).addCallback(lambda ignore: self.nextImport())
else:
self.iterator = self.createIterator()
reactor.addReader(self)
if deleteFile:
try:
print>>log, "[EPGImport] unlink", filename
os.unlink(filename)
except Exception, e:
print>>log, "[EPGImport] warning: Could not remove '%s' intermediate" % filename, e
开发者ID:sotocirus,项目名称:epg_SF_TEAM,代码行数:26,代码来源:EPGImport.py
示例7: startService
def startService(self):
self.tunDevice = pytun.TunTapDevice(flags=pytun.IFF_TUN|pytun.IFF_NO_PI)
self.tunDevice.addr = self.tun_local_ip
self.tunDevice.dstaddr = self.tun_remote_ip
self.tunDevice.netmask = self.tun_netmask
self.tunDevice.mtu = self.tun_mtu
# TODO: drop priveleges after bringing up interface
self.tunDevice.up()
# UDP <-> TUN
tun_consumer = TUNPacketConsumer(self.tunDevice)
udp_ConsumerProducerProxy = UDP_ConsumerProducerProxy(
consumer = tun_consumer,
local_ip = self.udp_local_ip,
local_port = self.udp_local_port,
remote_ip = self.udp_remote_ip,
remote_port = self.udp_remote_port)
tun_producer = TUNPacketProducer(self.tunDevice, consumer = udp_ConsumerProducerProxy)
reactor.listenUDP(self.udp_local_port, udp_ConsumerProducerProxy)
reactor.addReader(tun_producer)
开发者ID:kultus,项目名称:hushVPN,代码行数:27,代码来源:hushVPN_service.py
示例8: run
def run(self, stdscr):
"""
This method is called by the curses.wrapper to start the mainloop and
screen.
:param stdscr: curses screen passed in from curses.wrapper
"""
# We want to do an interactive session, so start up the curses screen and
# pass it the function that handles commands
colors.init_colors()
self.screen = screen.Screen(stdscr, self.do_command, self.tab_completer, self.encoding)
self.statusbars = StatusBars()
self.eventlog = EventLog()
self.screen.topbar = "{!status!}Deluge " + deluge.common.get_version() + " Console"
self.screen.bottombar = "{!status!}"
self.screen.refresh()
# The Screen object is designed to run as a twisted reader so that it
# can use twisted's select poll for non-blocking user input.
reactor.addReader(self.screen)
# Start the twisted mainloop
reactor.run()
开发者ID:pranav,项目名称:deluge,代码行数:25,代码来源:main.py
示例9: start_dns_queue
def start_dns_queue(self):
self.q = nfqueue.queue()
self.q.set_callback(self.nfqueue_callback)
self.q.fast_open(0, socket.AF_INET)
self.q.set_queue_maxlen(5000)
reactor.addReader(self)
self.q.set_mode(nfqueue.NFQNL_COPY_PACKET)
开发者ID:spnow,项目名称:MITMf,代码行数:7,代码来源:Spoof.py
示例10: __init__
def __init__(self, name, port):
self.rsock = pybonjour.DNSServiceRegister(name=name,
regtype="_hopper._tcp",
port=port,
callBack=self.register_callback,
domain="local.")
reactor.addReader(self)
开发者ID:0day1day,项目名称:HopperScripts,代码行数:7,代码来源:Hopper+GDB+to+GDB.py
示例11: __init__
def __init__(self, target, **settings):
self.target = target
self.settings = settings
self.verbose = settings.get("verbose")
self.proto = settings.get("proto")
self.rfd = socket.socket(socket.AF_INET, socket.SOCK_RAW,
socket.IPPROTO_ICMP)
if self.proto == "icmp":
self.sfd = socket.socket(socket.AF_INET, socket.SOCK_RAW,
socket.IPPROTO_ICMP)
elif self.proto == "udp":
self.sfd = socket.socket(socket.AF_INET, socket.SOCK_RAW,
socket.IPPROTO_UDP)
elif self.proto == "tcp":
self.sfd = socket.socket(socket.AF_INET, socket.SOCK_RAW,
socket.IPPROTO_TCP)
self.rfd.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
self.sfd.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
self.hops = []
self.out_queue = []
self.waiting = True
self.deferred = defer.Deferred()
reactor.addReader(self)
reactor.addWriter(self)
# send 1st probe packet
self.out_queue.append(Hop(self.target, 1,
settings.get("proto"),
self.settings.get("dport"),
self.settings.get("sport")))
开发者ID:RiverLiu,项目名称:txtraceroute,代码行数:33,代码来源:txtraceroute.py
示例12: twistedinteract
def twistedinteract(self):
from twisted.internet import reactor
from twisted.internet.abstract import FileDescriptor
import signal
outerself = self
class Me(FileDescriptor):
def fileno(self):
""" We want to select on FD 0 """
return 0
def doRead(self):
"""called when input is ready"""
try:
outerself.handle1()
except EOFError:
reactor.stop()
reactor.addReader(Me())
reactor.callWhenRunning(signal.signal,
signal.SIGINT,
signal.default_int_handler)
self.prepare()
try:
reactor.run()
finally:
self.restore()
开发者ID:c0710204,项目名称:mirrorsBistu,代码行数:26,代码来源:python_reader.py
示例13: start
def start():
from twisted.internet import reactor
global WATCHER
if not WATCHER:
WATCHER = FileWatcher()
reactor.addReader(FileWatcher())
return WATCHER
开发者ID:xythian,项目名称:shotlib,代码行数:7,代码来源:fileevents.py
示例14: __init__
def __init__(self, logfile=None ):
self.twisted_bdmclient = BdmClient()
output = BDMNormalOutput(logfile)
output.handle_callbacks()
reactor.addReader(self.twisted_bdmclient)
开发者ID:SebKuzminsky,项目名称:hammerhead,代码行数:7,代码来源:clienttest.py
示例15: __init__
def __init__(self, identity=None, default_recipient=None):
"""
Prepares ZMQ socket.
You can supply an identity to be able to bootstrap communication
by sending messages to well-known participants. Participants
sending most messages to a single recipient can set it as default
as ommit it's name when calling the send method.
Every message contains a timestamp that is checked by recipient.
If the time difference is larger than 15 seconds, message is dropped.
Make sure your machines use NTP to synchronize their clocks.
"""
# Create the 0MQ socket.
self.socket = zmq.Context.instance().socket(zmq.ROUTER)
# Assume either user-specified identity or generate our own.
if identity is not None:
self.socket.setsockopt(zmq.IDENTITY, identity)
else:
self.socket.setsockopt(zmq.IDENTITY, uuidgen())
# Remember the default recipient.
self.default_recipient = default_recipient
# Register ourselves with Twisted reactor loop.
reactor.addReader(self)
开发者ID:cloudcache,项目名称:python-ponycloud,代码行数:27,代码来源:tzmq.py
示例16: main
def main(stdscr):
parser = argparse.ArgumentParser()
parser.add_argument('user', type=str)
parser.add_argument('-v', '--verbose', action='count')
args = parser.parse_args()
user = args.user
server_name = origin_from_ucid(user)
## Set up logging ##
root_logger = logging.getLogger()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(lineno)d - '
'%(levelname)s - %(message)s')
if not os.path.exists("logs"):
os.makedirs("logs")
fh = logging.FileHandler("logs/%s" % user)
fh.setFormatter(formatter)
root_logger.addHandler(fh)
root_logger.setLevel(logging.DEBUG)
# Hack: The only way to get it to stop logging to sys.stderr :(
log.theLogPublisher.observers = []
observer = log.PythonLoggingObserver()
observer.start()
## Set up synapse server
curses_stdio = cursesio.CursesStdIO(stdscr)
input_output = InputOutput(curses_stdio, user)
curses_stdio.set_callback(input_output)
app_hs = SynapseHomeServer(server_name, db_name="dbs/%s" % user)
replication = app_hs.get_replication_layer()
hs = HomeServer(server_name, replication, curses_stdio)
input_output.set_home_server(hs)
## Add input_output logger
io_logger = IOLoggerHandler(input_output)
io_logger.setFormatter(formatter)
root_logger.addHandler(io_logger)
## Start! ##
try:
port = int(server_name.split(":")[1])
except:
port = 12345
app_hs.get_http_server().start_listening(port)
reactor.addReader(curses_stdio)
reactor.run()
开发者ID:0-T-0,项目名称:synapse,代码行数:59,代码来源:test_messaging.py
示例17: postOptions
def postOptions(self):
if hasattr(MouseMan, 'FAKE'):
raise TwistedTooOld, "Your twisted is too old to contain twisted.protocols.mice"
c = McFooClientMouseControl()
transport = SerialPort(self.opts['file'])
transport.protocol = McFooMouse(c)
reactor.addReader(transport)
c()
开发者ID:tv42,项目名称:mc-foo,代码行数:8,代码来源:mousecontrol.py
示例18: __init__
def __init__(self,task_num,address):
self.task_num=task_num
self.address=address
self.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.sock.connect(self.address)
self.sock.setblocking(0)
reactor.addReader(self)
开发者ID:chen19901225,项目名称:SimplePyCode,代码行数:8,代码来源:get_poetry.py
示例19: __init__
def __init__(self, parent, iface = 'any', filter = None, snaplen = 65535, promisc = False, timeout = 10):
self.parent = parent
self.pcap = pcap.pcapObject()
self.pcap.open_live(iface, snaplen, promisc, 0)
if filter is not None:
self.pcap.setfilter(filter, 1, 0)
self.pcap.setnonblock(True)
reactor.addReader(self)
开发者ID:PR2,项目名称:linux_networking,代码行数:8,代码来源:pcap_twisted.py
示例20: __init__
def __init__(self, args):
self.q = nfqueue.queue()
self.q.set_callback(Parser(args).start)
self.q.fast_open(0, socket.AF_INET)
self.q.set_queue_maxlen(5000)
reactor.addReader(self)
self.q.set_mode(nfqueue.NFQNL_COPY_PACKET)
print '[*] Flushed 防火墙 和转发流量 到队列 ; 等待数据 '
开发者ID:AbbySec,项目名称:WifiAttack,代码行数:8,代码来源:WifiAttack.py
注:本文中的twisted.internet.reactor.addReader函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论