1
0
mirror of https://github.com/RIOT-OS/RIOT.git synced 2025-01-18 12:52:44 +01:00

Merge pull request #8303 from aabadie/pr/flake8/pyterm

dist/tools/pyterm: fix flake8 issues
This commit is contained in:
Sebastian Meiling 2018-01-12 15:29:41 +01:00 committed by GitHub
commit 21ff9ac98c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 67 additions and 48 deletions

View File

@ -19,7 +19,7 @@ DIST_TOOLS=${RIOTBASE:-.}/dist/tools
. ${DIST_TOOLS}/ci/changed_files.sh . ${DIST_TOOLS}/ci/changed_files.sh
FILES=$(FILEREGEX='*.py$' changed_files) FILES=$(FILEREGEX='(?=*.py$|pyterm$)' changed_files)
if [ -z "${FILES}" ] if [ -z "${FILES}" ]
then then

View File

@ -24,8 +24,19 @@ try:
except ImportError: except ImportError:
import ConfigParser as configparser import ConfigParser as configparser
import cmd, serial, socket, sys, threading, readline, time, logging, \ import cmd
os, argparse, re, codecs, signal 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: try:
serial.Serial serial.Serial
@ -57,7 +68,6 @@ except ImportError:
pass pass
# set some default options # set some default options
import platform
defaulthostname = platform.node() defaulthostname = platform.node()
# default serial port # default serial port
@ -122,7 +132,7 @@ class SerCmd(cmd.Cmd):
self.log_dir_name = log_dir_name self.log_dir_name = log_dir_name
self.newline = newline self.newline = newline
self.serprompt = serprompt self.serprompt = serprompt
if not formatter is None: if formatter is not None:
self.fmt_str = formatter self.fmt_str = formatter
if not self.host: if not self.host:
@ -239,9 +249,9 @@ class SerCmd(cmd.Cmd):
# wait until connection is established and fire startup # wait until connection is established and fire startup
# commands to the node # commands to the node
time.sleep(1) time.sleep(1)
for cmd in self.init_cmd: for command in self.init_cmd:
self.logger.debug("WRITE ----->>>>>> '" + cmd + "'\n") self.logger.debug("WRITE ----->>>>>> '" + command + "'\n")
self.onecmd(self.precmd(cmd)) self.onecmd(self.precmd(command))
# start serial->console thread # start serial->console thread
receiver_thread = threading.Thread(target=self.reader) receiver_thread = threading.Thread(target=self.reader)
@ -609,7 +619,7 @@ class SerCmd(cmd.Cmd):
errors='replace') errors='replace')
c = sr.read(1) c = sr.read(1)
# try to re-open it with a timeout of 1s otherwise # 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 " self.logger.warn("Serial port disconnected, waiting to "
"get reconnected...") "get reconnected...")
self.ser.close() self.ser.close()
@ -620,7 +630,7 @@ class SerCmd(cmd.Cmd):
try: try:
self.serial_connect() self.serial_connect()
self.logger.info("Reconnected to serial port %s" % self.port) self.logger.info("Reconnected to serial port %s" % self.port)
except serial.SerialException as se: except serial.SerialException:
pass pass
continue continue
if c == '\r': if c == '\r':
@ -698,6 +708,7 @@ class fdsocket(socket.socket):
self.close() self.close()
sys.exit(0) sys.exit(0)
if __name__ == "__main__": if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Pyterm - The Python " parser = argparse.ArgumentParser(description="Pyterm - The Python "
@ -757,7 +768,7 @@ if __name__ == "__main__":
args = parser.parse_args() args = parser.parse_args()
if (args.noprefix): if args.noprefix:
args.format = "" args.format = ""
myshell = SerCmd(args.port, args.baudrate, args.toggle, args.tcp_serial, myshell = SerCmd(args.port, args.baudrate, args.toggle, args.tcp_serial,
args.directory, args.config, args.host, args.run_name, args.directory, args.config, args.host, args.run_name,

View File

@ -19,7 +19,7 @@
# 02110-1301 USA # 02110-1301 USA
import sys, signal, threading import signal
from twisted.internet import reactor from twisted.internet import reactor
from twisted.internet.protocol import Protocol, Factory from twisted.internet.protocol import Protocol, Factory
@ -33,10 +33,8 @@ class PubProtocol(Protocol):
print("new connection made") print("new connection made")
def connectionLost(self, reason): def connectionLost(self, reason):
self.factory.numProtocols = self.factory.numProtocols - 1 self.factory.clients = {
key: value for key, value in self.factory.clients.items()
def connectionLost(self, reason):
self.factory.clients = {key: value for key, value in self.factory.clients.items()
if value is not self.transport} if value is not self.transport}
def dataReceived(self, data): def dataReceived(self, data):
@ -47,6 +45,7 @@ class PubProtocol(Protocol):
else: else:
print("received some useless data...") print("received some useless data...")
class PubFactory(Factory): class PubFactory(Factory):
def __init__(self): def __init__(self):
self.clients = dict() self.clients = dict()
@ -78,10 +77,9 @@ class ExperimentRunner():
if reactor.running: if reactor.running:
try: try:
reactor.stop() reactor.stop()
except: except Exception:
print("tried to shutdown reactor twice!") print("tried to shutdown reactor twice!")
def handle_sigint(self, signal, frame): def handle_sigint(self, signal, frame):
self.experiment.stop() self.experiment.stop()
self.testbed.stop() self.testbed.stop()
@ -138,10 +136,10 @@ class Experiment():
while (time() - start < seconds): while (time() - start < seconds):
sleep(seconds - (time() - start)) sleep(seconds - (time() - start))
def callLater(self, absoluteDelay = 0.0, function = None): def callLater(self, absoluteDelay=0.0, function=None):
reactor.callLater(absoluteDelay, function) reactor.callLater(absoluteDelay, function)
def waitAndCall(self, relativeDelay = 0.0, function = None): def waitAndCall(self, relativeDelay=0.0, function=None):
self.sumDelay += relativeDelay self.sumDelay += relativeDelay
self.callLater(self.sumDelay, function) self.callLater(self.sumDelay, function)

View File

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