1
0
mirror of https://github.com/RIOT-OS/RIOT.git synced 2024-12-29 04:50:03 +01:00

dist/tools/pyterm: fix flakes8 issues

This commit is contained in:
Alexandre Abadie 2018-01-05 13:41:40 +01:00
parent c20948df09
commit eaee364a1b
3 changed files with 63 additions and 42 deletions

View File

@ -24,8 +24,19 @@ try:
except ImportError:
import ConfigParser as configparser
import cmd, serial, socket, sys, threading, readline, time, logging, \
os, argparse, re, codecs, signal
import cmd
import serial
import socket
import sys
import threading
import readline
import time
import logging
import os
import argparse
import re
import codecs
import platform
try:
serial.Serial
@ -57,23 +68,22 @@ except ImportError:
pass
# set some default options
import platform
defaulthostname = platform.node()
# default serial port
defaultport = "/dev/ttyUSB0"
defaultport = "/dev/ttyUSB0"
# default baudrate for serial connection
defaultbaud = 115200
defaultbaud = 115200
# directory to store configuration and log files
defaultdir = os.environ['HOME'] + os.path.sep + '.pyterm'
defaultdir = os.environ['HOME'] + os.path.sep + '.pyterm'
# configuration file name
defaultfile = "pyterm-" + defaulthostname + ".conf"
defaultfile = "pyterm-" + defaulthostname + ".conf"
# logging subfolder
defaultrunname = "default-run"
defaultrunname = "default-run"
# default logging prefix format string
default_fmt_str = '%(asctime)s - %(levelname)s # %(message)s'
@ -82,7 +92,7 @@ default_fmt_str = '%(asctime)s - %(levelname)s # %(message)s'
defaultnewline = "LF"
# default prompt character
defaultprompt = '>'
defaultprompt = '>'
class SerCmd(cmd.Cmd):
@ -122,7 +132,7 @@ class SerCmd(cmd.Cmd):
self.log_dir_name = log_dir_name
self.newline = newline
self.serprompt = serprompt
if not formatter is None:
if formatter is not None:
self.fmt_str = formatter
if not self.host:
@ -239,9 +249,9 @@ class SerCmd(cmd.Cmd):
# wait until connection is established and fire startup
# commands to the node
time.sleep(1)
for cmd in self.init_cmd:
self.logger.debug("WRITE ----->>>>>> '" + cmd + "'\n")
self.onecmd(self.precmd(cmd))
for command in self.init_cmd:
self.logger.debug("WRITE ----->>>>>> '" + command + "'\n")
self.onecmd(self.precmd(command))
# start serial->console thread
receiver_thread = threading.Thread(target=self.reader)
@ -480,7 +490,7 @@ class SerCmd(cmd.Cmd):
self.config = configparser.SafeConfigParser()
cf = os.path.join(self.configdir, self.configfile)
self.config.read(cf)
logging.getLogger("").info("Reading file: %s" % cf)
logging.getLogger("").info("Reading file: %s" % cf)
for sec in self.config.sections():
if sec == "filters":
@ -609,7 +619,7 @@ class SerCmd(cmd.Cmd):
errors='replace')
c = sr.read(1)
# try to re-open it with a timeout of 1s otherwise
except (serial.SerialException, ValueError) as se:
except (serial.SerialException, ValueError):
self.logger.warn("Serial port disconnected, waiting to "
"get reconnected...")
self.ser.close()
@ -620,7 +630,7 @@ class SerCmd(cmd.Cmd):
try:
self.serial_connect()
self.logger.info("Reconnected to serial port %s" % self.port)
except serial.SerialException as se:
except serial.SerialException:
pass
continue
if c == '\r':
@ -698,6 +708,7 @@ class fdsocket(socket.socket):
self.close()
sys.exit(0)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Pyterm - The Python "
@ -757,7 +768,7 @@ if __name__ == "__main__":
args = parser.parse_args()
if (args.noprefix):
if args.noprefix:
args.format = ""
myshell = SerCmd(args.port, args.baudrate, args.toggle, args.tcp_serial,
args.directory, args.config, args.host, args.run_name,

View File

@ -19,7 +19,7 @@
# 02110-1301 USA
import sys, signal, threading
import signal
from twisted.internet import reactor
from twisted.internet.protocol import Protocol, Factory
@ -45,6 +45,7 @@ class PubProtocol(Protocol):
else:
print("received some useless data...")
class PubFactory(Factory):
def __init__(self):
self.clients = dict()
@ -76,14 +77,13 @@ class ExperimentRunner():
if reactor.running:
try:
reactor.stop()
except:
except Exception:
print("tried to shutdown reactor twice!")
def handle_sigint(self, signal, frame):
self.experiment.stop()
self.testbed.stop()
self.stop() # shutdown if experiment didn't already
self.stop() # shutdown if experiment didn't already
class Experiment():
@ -127,7 +127,7 @@ class Experiment():
print("sendToHost: no such host known: " + host + " !")
def sendToAll(self, cmd=""):
for host, transport in self.factory.clients.items():
for host, transport in self.factory.clients.items():
self.sendToHost(host, cmd)
def pauseInSeconds(self, seconds=0):
@ -136,10 +136,10 @@ class Experiment():
while (time() - start < seconds):
sleep(seconds - (time() - start))
def callLater(self, absoluteDelay = 0.0, function = None):
def callLater(self, absoluteDelay=0.0, function=None):
reactor.callLater(absoluteDelay, function)
def waitAndCall(self, relativeDelay = 0.0, function = None):
def waitAndCall(self, relativeDelay=0.0, function=None):
self.sumDelay += relativeDelay
self.callLater(self.sumDelay, function)

View File

@ -19,7 +19,9 @@
# 02110-1301 USA
import os, re, datetime
import os
import re
import datetime
from subprocess import call, Popen, PIPE
@ -45,7 +47,7 @@ class Testbed():
def cleanLogs(self):
raise NotImplementedError("Inherit from Testbed and implement flashNodes")
def archiveLogs(self, experiment = None):
def archiveLogs(self, experiment=None):
raise NotImplementedError("Inherit from Testbed and implement flashNodes")
def start(self):
@ -54,11 +56,11 @@ class Testbed():
def stop(self):
raise NotImplementedError("Inherit from Testbed and implement flashNodes")
def defaultArchivePostfix(self, experimentName = None):
def defaultArchivePostfix(self, experimentName=None):
if not experimentName:
experimentName = "unknown"
time = datetime.datetime.now().strftime("%Y-%m-%d_%H_%M_%S")
postfix = "-" + experimentName +"_" + time
postfix = "-" + experimentName + "_" + time
return postfix
def printAndCall(self, cmdString):
@ -67,8 +69,8 @@ class Testbed():
class DESTestbed(Testbed):
def __init__(self, serverHost = None, serverPort=None, userName = None, flasher = None,
hexfilePath = None, pyterm = None, logFilePath = None, hostFile = None):
def __init__(self, serverHost=None, serverPort=None, userName=None, flasher=None,
hexfilePath=None, pyterm=None, logFilePath=None, hostFile=None):
self.serverHost = serverHost
self.serverPort = str(serverPort)
self.userName = userName
@ -84,19 +86,22 @@ class DESTestbed(Testbed):
def cleanLogs(self):
self.printAndCall("rm -rf %s/*.log" % (self.logFilePath))
def archiveLogs(self, postfix = None):
def archiveLogs(self, postfix=None):
postfix = self.defaultArchivePostfix(postfix)
logDir = self.logFilePath.split("/")[-1]
self.printAndCall("cd %s/..; tar -cjf archived_logs%s.tar.bz2 %s/*.log" % (self.logFilePath, postfix, logDir))
def start(self):
self.printAndCall("parallel-ssh -h %s -l %s 'screen -S pyterm -d -m python %s -ln %s'" % (self.hostFile, self.userName, self.pyterm, self.log_dir_name))
self.printAndCall("parallel-ssh -h %s -l %s 'screen -S pyterm -d -m python %s -ln %s'"
% (self.hostFile, self.userName, self.pyterm, self.log_dir_name))
def stop(self):
self.printAndCall("parallel-ssh -h %s -l %s 'screen -X -S pyterm quit'" % (self.hostFile, self.userName))
class LocalTestbed(Testbed):
def __init__(self, serverHost = None, serverPort=None, flasher = None, hexfilePath = None, pyterm = None, logFilePath = None):
def __init__(self, serverHost=None, serverPort=None, flasher=None,
hexfilePath=None, pyterm=None, logFilePath=None):
self.serverHost = serverHost
self.serverPort = str(serverPort)
self.flasher = flasher
@ -115,7 +120,7 @@ class LocalTestbed(Testbed):
def cleanLogs(self):
self.printAndCall("rm -rf %s/*.log" % (self.logFilePath))
def archiveLogs(self, postfix = None):
def archiveLogs(self, postfix=None):
postfix = self.defaultArchivePostfix(postfix)
logDir = self.logFilePath.split("/")[-1]
self.printAndCall("cd %s/..; tar -cjf archived_logs%s.tar.bz2 %s/*.log" % (self.logFilePath, postfix, logDir))
@ -123,15 +128,18 @@ class LocalTestbed(Testbed):
def start(self):
portList = self.findPorts()
for port in portList:
self.printAndCall("screen -S pyterm-%s -d -m python %s -H %s -rn %s -p /dev/%s -ln %s" % (port, self.pyterm, port, port, port, self.log_dir_name))
self.printAndCall("screen -S pyterm-%s -d -m python %s -H %s -rn %s -p /dev/%s -ln %s"
% (port, self.pyterm, port, port, port, self.log_dir_name))
def stop(self):
portList = self.findPorts()
for port in portList:
self.printAndCall("screen -X -S pyterm-%s quit" % (port))
class DesVirtTestbed(Testbed):
def __init__(self, serverHost = None, serverPort=None, desvirtPath = None, topologyName = None, pyterm = None, logFilePath = None):
def __init__(self, serverHost=None, serverPort=None, desvirtPath=None,
topologyName=None, pyterm=None, logFilePath=None):
self.serverHost = serverHost
self.serverPort = str(serverPort)
self.desvirtPath = desvirtPath
@ -144,9 +152,10 @@ class DesVirtTestbed(Testbed):
return self.namePortList
def startDesVirtNetwork(self):
print "executing: " + "./vnet --start --name " + self.topologyName + " in: " + self.desvirtPath
print("executing: " + "./vnet --start --name " + self.topologyName + " in: " + self.desvirtPath)
call("sh -c \"./vnet --define --name " + self.topologyName + "\"", cwd=self.desvirtPath, shell=True)
stream = Popen("sh -c \"./vnet --start --name " + self.topologyName + "\"", cwd=self.desvirtPath, shell=True, stderr=PIPE).stderr
stream = Popen("sh -c \"./vnet --start --name " + self.topologyName + "\"",
cwd=self.desvirtPath, shell=True, stderr=PIPE).stderr
pats = r'.*riotnative.*\.elf (\S+) -t (\S+)'
pattern = re.compile(pats)
for line in stream:
@ -156,7 +165,7 @@ class DesVirtTestbed(Testbed):
self.namePortList.append((tuple[0], int(tuple[1])))
self.namePortList = sorted(self.namePortList)
for tuple in self.namePortList:
print "name: " + tuple[0] + " port: " + str(tuple[1])
print("name: " + tuple[0] + " port: " + str(tuple[1]))
def stopDesVirtNetwork(self):
call("sh -c \"./vnet --stop --name " + self.topologyName + "\"", cwd=self.desvirtPath, shell=True)
@ -167,17 +176,18 @@ class DesVirtTestbed(Testbed):
def cleanLogs(self):
self.printAndCall("rm -rf %s/*.log" % (self.logFilePath))
def archiveLogs(self, postfix = None):
def archiveLogs(self, postfix=None):
postfix = self.defaultArchivePostfix(postfix)
logDir = self.logFilePath.split("/")[-1]
self.printAndCall("cd %s/..; tar -cjf archived_logs%s.tar.bz2 %s/*.log" % (self.logFilePath, postfix, logDir))
def start(self):
for node in self.namePortList:
self.printAndCall("screen -S pyterm-%s -d -m python %s -H %s -rn %s -ts %s -ln %s" % (node[0], self.pyterm, node[0], node[0], node[1], self.log_dir_name))
self.printAndCall("screen -S pyterm-%s -d -m python %s -H %s -rn %s -ts %s -ln %s"
% (node[0], self.pyterm, node[0], node[0], node[1], self.log_dir_name))
def stop(self):
print "stop called"
print("stop called")
for node in self.namePortList:
self.printAndCall("screen -X -S pyterm-%s quit" % (node[0]))
self.stopDesVirtNetwork()