本文整理汇总了Python中mininet.log.output函数的典型用法代码示例。如果您正苦于以下问题:Python output函数的具体用法?Python output怎么用?Python output使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了output函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: errRun
def errRun( *cmd, **kwargs ):
"""Run a command and return stdout, stderr and return code
cmd: string or list of command and args
stderr: STDOUT to merge stderr with stdout
shell: run command using shell
echo: monitor output to console"""
# By default we separate stderr, don't run in a shell, and don't echo
stderr = kwargs.get( 'stderr', PIPE )
shell = kwargs.get( 'shell', False )
echo = kwargs.get( 'echo', False )
if echo:
# cmd goes to stderr, output goes to stdout
info( cmd, '\n' )
if len( cmd ) == 1:
cmd = cmd[ 0 ]
# Allow passing in a list or a string
if isinstance( cmd, str ) and not shell:
cmd = cmd.split( ' ' )
cmd = [ str( arg ) for arg in cmd ]
elif isinstance( cmd, list ) and shell:
cmd = " ".join( arg for arg in cmd )
debug( '*** errRun:', cmd, '\n' )
popen = Popen( cmd, stdout=PIPE, stderr=stderr, shell=shell )
# We use poll() because select() doesn't work with large fd numbers,
# and thus communicate() doesn't work either
out, err = '', ''
poller = poll()
poller.register( popen.stdout, POLLIN )
fdtofile = { popen.stdout.fileno(): popen.stdout }
outDone, errDone = False, True
if popen.stderr:
fdtofile[ popen.stderr.fileno() ] = popen.stderr
poller.register( popen.stderr, POLLIN )
errDone = False
while not outDone or not errDone:
readable = poller.poll()
for fd, event in readable:
f = fdtofile[ fd ]
if event & POLLIN:
data = f.read( 1024 )
if echo:
output( data )
if f == popen.stdout:
out += data
if data == '':
outDone = True
elif f == popen.stderr:
err += data
if data == '':
errDone = True
else: # POLLHUP or something unexpected
if f == popen.stdout:
outDone = True
elif f == popen.stderr:
errDone = True
poller.unregister( fd )
returncode = popen.wait()
debug( out, err, returncode )
return out, err, returncode
示例2: waitForNode
def waitForNode( self, node ):
"Wait for a node to finish, and print its output."
# Pollers
nodePoller = poll()
nodePoller.register( node.stdout )
bothPoller = poll()
bothPoller.register( self.stdin, POLLIN )
bothPoller.register( node.stdout, POLLIN )
if self.isatty():
# Buffer by character, so that interactive
# commands sort of work
quietRun( 'stty -icanon min 1' )
while True:
try:
bothPoller.poll()
# XXX BL: this doesn't quite do what we want.
if False and self.inputFile:
key = self.inputFile.read( 1 )
if key is not '':
node.write(key)
else:
self.inputFile = None
if isReadable( self.inPoller ):
key = self.stdin.read( 1 )
node.write( key )
if isReadable( nodePoller ):
data = node.monitor()
output( data )
if not node.waiting:
break
except KeyboardInterrupt:
node.sendInt()
示例3: ping
def ping(self, hosts=None):
"""Ping between all specified hosts.
hosts: list of hosts
returns: ploss packet loss percentage"""
# should we check if running?
packets = 0
lost = 0
ploss = None
if not hosts:
hosts = self.hosts
output("*** Ping: testing ping reachability\n")
for node in hosts:
# print "node:" ,node # only test~lol
output("%s -> " % node.name)
for dest in hosts:
if node != dest:
result = node.cmd("ping -c1 " + dest.IP())
sent, received = self._parsePing(result)
packets += sent
if received > sent:
error("*** Error: received too many packets")
error("%s" % result)
node.cmdPrint("route")
exit(1)
lost += sent - received
output(("%s " % dest.name) if received else "X ")
output("\n")
ploss = 100 * lost / packets
output("*** Results: %i%% dropped (%d/%d lost)\n" % (ploss, lost, packets))
return ploss
示例4: ping
def ping( self, hosts=None, timeout=None ):
"""Ping between all specified hosts.
hosts: list of hosts
timeout: time to wait for a response, as string
returns: ploss packet loss percentage"""
# should we check if running?
packets = 0
lost = 0
ploss = None
if not hosts:
hosts = self.hosts[1:]
output( '*** Ping: testing ping reachability\n' )
for node in hosts:
output( '%s -> ' % node.name )
for dest in hosts:
if node != dest:
opts = ''
if timeout:
opts = '-W %s' % timeout
result = node.cmd( 'ping -c1 %s %s' % (opts, dest.IP()) )
sent, received = self._parsePing( result )
packets += sent
if received > sent:
error( '*** Error: received too many packets' )
error( '%s' % result )
node.cmdPrint( 'route' )
exit( 1 )
lost += sent - received
output( ( '%s ' % dest.name ) if received else 'X ' )
output( '\n' )
ploss = 100 * lost / packets
output( "*** Results: %i%% dropped (%d/%d lost)\n" %
( ploss, lost, packets ) )
return ploss
示例5: do_bgIperf
def do_bgIperf(self, line):
args = line.split()
if not args:
output("Provide a list of hosts.\n")
# Try to parse the '-t' argument as the number of seconds
seconds = 10
for i, arg in enumerate(args):
if arg == "-t":
if i + 1 < len(args):
try:
seconds = int(args[i + 1])
except ValueError:
error("Could not parse number of seconds: %s", args[i + 1])
del (args[i + 1])
del args[i]
hosts = []
err = False
for arg in args:
if arg not in self.mn:
err = True
error("node '%s' not in network\n" % arg)
else:
hosts.append(self.mn[arg])
if "bgIperf" in dir(self.mn) and not err:
self.mn.bgIperf(hosts, seconds=seconds)
示例6: runCpuLimitTest
def runCpuLimitTest(self, cpu, duration=5):
"""run CPU limit test with 'while true' processes.
cpu: desired CPU fraction of each host
duration: test duration in seconds
returns a single list of measured CPU fractions as floats.
"""
pct = cpu * 100
info("*** Testing CPU %.0f%% bandwidth limit\n" % pct)
hosts = self.hosts
for h in hosts:
h.cmd("while true; do a=1; done &")
pids = [h.cmd("echo $!").strip() for h in hosts]
pids_str = ",".join(["%s" % pid for pid in pids])
cmd = "ps -p %s -o pid,%%cpu,args" % pids_str
# It's a shame that this is what pylint prefers
outputs = []
for _ in range(duration):
sleep(1)
outputs.append(quietRun(cmd).strip())
for h in hosts:
h.cmd("kill $!")
cpu_fractions = []
for test_output in outputs:
# Split by line. Ignore first line, which looks like this:
# PID %CPU COMMAND\n
for line in test_output.split("\n")[1:]:
r = r"\d+\s*(\d+\.\d+)"
m = re.search(r, line)
if m is None:
error("*** Error: could not extract CPU fraction: %s\n" % line)
return None
cpu_fractions.append(float(m.group(1)))
output("*** Results: %s\n" % cpu_fractions)
return cpu_fractions
示例7: do_placement
def do_placement(self, _line):
"Describe node placement"
mn = self.mn
nodes = mn.hosts + mn.switches + mn.controllers
for server in mn.servers:
names = [n.name for n in nodes if hasattr(n, "server") and n.server == server]
output("%s: %s\n" % (server, " ".join(names)))
示例8: PMUPingPDC
def PMUPingPDC(net, pmu, pdc, timeout):
time.sleep(5)
pmu_host = net.getNodeByName(pmu)
pdc_host = net.getNodeByName(pdc)
output('%s(%s) ping -c1 %s(%s)' % (pmu, pmu_host.IP(), pdc, pdc_host.IP()))
result = pmu_host.cmd('ping -W %d -c1 %s' % (timeout, pdc_host.IP()))
output(result)
示例9: waitForNode
def waitForNode( self, node ):
"Wait for a node to finish, and print its output."
# Pollers
nodePoller = poll()
nodePoller.register( node.stdout )
bothPoller = poll()
bothPoller.register( self.stdin )
bothPoller.register( node.stdout )
while True:
try:
bothPoller.poll()
# XXX BL: this doesn't quite do what we want.
if False and self.inputFile:
key = self.inputFile.read( 1 )
if key is not '':
node.write(key)
else:
self.inputFile = None
if isReadable( self.inPoller ):
key = self.stdin.read( 1 )
node.write( key )
if isReadable( nodePoller ):
data = node.monitor()
output( data )
if not node.waiting:
break
except KeyboardInterrupt:
node.sendInt()
示例10: __init__
def __init__( self, mininet, stdin=sys.stdin, script=None ):
self.mn = mininet
self.nodelist = self.mn.controllers + self.mn.switches + self.mn.hosts
self.nodemap = {} # map names to Node objects
for node in self.nodelist:
self.nodemap[ node.name ] = node
# Attempt to handle input
self.stdin = stdin
self.inPoller = poll()
self.inPoller.register( stdin )
self.inputFile = script
Cmd.__init__( self )
info( '*** Starting CLI:\n' )
if self.inputFile:
self.do_source( self.inputFile )
return
while True:
try:
# Make sure no nodes are still waiting
for node in self.nodelist:
while node.waiting:
node.sendInt()
node.monitor()
if self.isatty():
quietRun( 'stty sane' )
self.cmdloop()
break
except KeyboardInterrupt:
output( '\nInterrupt\n' )
示例11: hostPing
def hostPing(self, rate, duration_time=10):
# rate is the arp request per secend per host
rate = float(rate)
host_numb = len(self.hosts)
output("host_numb:%d\n" % host_numb)
net_rate = int(host_numb * rate)
self.netPing(net_rate, duration_time)
示例12: do_px
def do_px( self, line ):
"""Execute a Python statement.
Node names may be used, e.g.: px print h1.cmd('ls')"""
try:
exec( line, globals(), self.getLocals() )
except Exception, e:
output( str( e ) + '\n' )
示例13: __init__
def __init__( self, mininet, stdin=sys.stdin, script=None ):
self.mn = mininet
# Local variable bindings for py command
self.locals = { 'net': mininet }
# Attempt to handle input
self.stdin = stdin
self.inPoller = poll()
self.inPoller.register( stdin )
self.inputFile = script
Cmd.__init__( self )
info( '*** Starting CLI:\n' )
if self.inputFile:
self.do_source( self.inputFile )
return
while True:
try:
# Make sure no nodes are still waiting
for node in self.mn.values():
while node.waiting:
node.sendInt()
node.monitor()
if self.isatty():
quietRun( 'stty sane' )
self.cmdloop()
break
except KeyboardInterrupt:
output( '\nInterrupt\n' )
示例14: build
def build(self, ovs_type, ports_sock, test_name, dpids,
n_tagged=0, tagged_vid=100, n_untagged=0, links_per_host=0,
n_extended=0, e_cls=None, tmpdir=None, hw_dpid=None, host_namespace=None):
if not host_namespace:
host_namespace = {}
for dpid in dpids:
serialno = mininet_test_util.get_serialno(
ports_sock, test_name)
sid_prefix = self._get_sid_prefix(serialno)
for host_n in range(n_tagged):
self._add_tagged_host(sid_prefix, tagged_vid, host_n)
for host_n in range(n_untagged):
self._add_untagged_host(sid_prefix, host_n, host_namespace.get(host_n, True))
for host_n in range(n_extended):
self._add_extended_host(sid_prefix, host_n, e_cls, tmpdir)
switch_cls = FaucetSwitch
if hw_dpid and hw_dpid == dpid:
remap_dpid = str(int(dpid) + 1)
output('bridging hardware switch DPID %s (%x) dataplane via OVS DPID %s (%x)' % (
dpid, int(dpid), remap_dpid, int(remap_dpid)))
dpid = remap_dpid
switch_cls = NoControllerFaucetSwitch
switch = self._add_faucet_switch(sid_prefix, dpid, ovs_type, switch_cls)
self._add_links(switch, self.hosts(), links_per_host)
示例15: waitListening
def waitListening(client, server, port):
"Wait until server is listening on port"
if not "telnet" in client.cmd("which telnet"):
raise Exception("Could not find telnet")
cmd = 'sh -c "echo A | telnet -e A %s %s"' % (server.IP(), port)
while "Connected" not in client.cmd(cmd):
output("waiting for", server, "to listen on port", port, "\n")
sleep(0.5)