Fix python style issues reported by flake8

Additionally some python2-only "print" statements are now compatible
with python3.
This commit is contained in:
Lars Kruse 2019-12-18 00:25:39 +01:00
parent 73f885e382
commit 7063330e03
17 changed files with 102 additions and 103 deletions

View File

@ -100,7 +100,7 @@ def parse(clients):
# Get the current bytes
if line.endswith(" is running."):
bytes_count_text = input_lines[pos+2].split()[1].split("=")[1].replace(",", "")
bytes_count_text = input_lines[pos + 2].split()[1].split("=")[1].replace(",", "")
try:
# python2
bytes_count = long(bytes_count_text)
@ -126,8 +126,8 @@ def print_config():
print("graph_category backup")
print("graph_order", " ".join(fd[1] for fd in clients))
print()
if ((os.getenv("report_hostname") is not None) and
(os.getenv("report_hostname").upper() in ["YES", "TRUE", "1", "Y"])):
if ((os.getenv("report_hostname") is not None)
and (os.getenv("report_hostname").upper() in ["YES", "TRUE", "1", "Y"])):
print("host_name", hostname)
for client in clients:
print("%s.label %s" % (client[1], client[0]))

View File

@ -91,7 +91,7 @@ def parse():
# Get the current bytes
if input_lines[pos].endswith("is mounted with:"):
bytes_count_text = input_lines[pos+5].split()[1].split("=")[1].replace(",", "")
bytes_count_text = input_lines[pos + 5].split()[1].split("=")[1].replace(",", "")
try:
bytes_count = long(bytes_count_text)
except NameError:

View File

@ -236,7 +236,7 @@ class Proxy:
'method': self.method,
'params': args,
'id': self.id,
}
}
request = urllib.request.Request(self.service.url, json.dumps(data).encode())
if self.service.username:
auth_string = '%s:%s' % (self.service.username, self.service.password)

View File

@ -7,11 +7,11 @@ import urllib2
import json
URL = 'https://www.btcguild.com/api.php?api_key='
API_KEY = sys.argv[0][(sys.argv[0].rfind('_')+1):]
API_KEY = sys.argv[0][(sys.argv[0].rfind('_') + 1):]
STATS = URL + API_KEY
print STATS
print(STATS)
command = ''
if len(sys.argv) > 1:
@ -25,16 +25,16 @@ workers = mining_stats['workers']
if command == 'config':
print "graph_title BTCGuild Hashrate"
print "graph_args --upper-limit 3000 -l 0"
print "graph_vlabel MHash/s"
print "graph_category htc"
print("graph_title BTCGuild Hashrate")
print("graph_args --upper-limit 3000 -l 0")
print("graph_vlabel MHash/s")
print("graph_category htc")
for worker in workers:
label = workers[worker]['worker_name']
print label + ".label " + label
print(label + ".label " + label)
sys.exit(0)
for worker in workers:
hash_rate = workers[worker]['hash_rate']
label = workers[worker]['worker_name']
print label + ".value %d" % int(hash_rate)
hash_rate = workers[worker]['hash_rate']
label = workers[worker]['worker_name']
print(label + ".value %d" % int(hash_rate))

View File

@ -53,7 +53,7 @@ import urllib2
program = sys.argv[0]
graph_type = program[program.rfind("_")+1:]
graph_type = program[program.rfind("_") + 1:]
graph_types = {
"accesses": [
{
@ -91,21 +91,21 @@ graph_types = {
if len(sys.argv) == 2 and sys.argv[1] == "autoconf":
print "yes"
print("yes")
elif len(sys.argv) == 2 and sys.argv[1] == "config":
if graph_type not in graph_types.keys():
raise Exception("Unknown graph type '%s'" % graph_type)
params = graph_types[graph_type]
for item in params:
print "graph_title %s" % item["title"]
print "graph_category webserver"
print("graph_title %s" % item["title"])
print("graph_category webserver")
for field in item["fields"]:
print "%s.label %s" % (field, field)
print "%s.type %s" % (field, item["type"])
print "graph_args %s" % item["args"]
print("%s.label %s" % (field, field))
print("%s.type %s" % (field, item["type"]))
print("graph_args %s" % item["args"])
elif len(sys.argv) == 2 and sys.argv[1] == "suggest":
for item in graph_types.keys():
print item
print(item)
else:
status_url = os.environ.get('status_url', 'http://127.0.0.1/server-status')
@ -129,11 +129,11 @@ else:
pass
if graph_type == "accesses":
print "accesses.value %s" % data["Total Accesses"]
print("accesses.value %s" % data["Total Accesses"])
elif graph_type == "kbytes":
print "kbytes.value %s" % data["Total kBytes"]
print("kbytes.value %s" % data["Total kBytes"])
elif graph_type == "uptime":
print "uptime.value %s" % str(float(data["Uptime"])/86400)
print("uptime.value %s" % str(float(data["Uptime"]) / 86400))
elif graph_type == "status":
print "busy.value %s" % data["BusyServers"]
print "idle.value %s" % data["IdleServers"]
print("busy.value %s" % data["BusyServers"])
print("idle.value %s" % data["IdleServers"])

View File

@ -54,7 +54,7 @@ import time
# How we've been called
progName = sys.argv[0]
progName = progName[progName.rfind("/")+1:]
progName = progName[progName.rfind("/") + 1:]
# Where to store plugin state

View File

@ -53,31 +53,31 @@ filterwarnings('ignore', category=MySQLdb.Warning)
program_name = os.path.basename(__file__)
variables = {
'percona_queues': {
'label': 'Queue sizes',
'vlabel': 'size',
'fields': ['wsrep_local_recv_queue', 'wsrep_local_send_queue']
},
'percona_flow': {
'label': 'Flow control',
'vlabel': '',
'fields': ['wsrep_flow_control_sent', 'wsrep_flow_control_recv']
},
'percona_transactions': {
'label': 'Transactions in and out',
'vlabel': 'transactions',
'fields': ['wsrep_replicated', 'wsrep_received']
},
'percona_transactions_bytes': {
'label': 'Transactions in and out in bytes',
'vlabel': 'bytes',
'fields': ['wsrep_replicated_bytes', 'wsrep_received_bytes']
},
'percona_replication': {
'label': 'Replication conflicts',
'vlabel': 'conflicts',
'fields': ['wsrep_local_cert_failures', 'wsrep_local_bf_aborts'],
}
'percona_queues': {
'label': 'Queue sizes',
'vlabel': 'size',
'fields': ['wsrep_local_recv_queue', 'wsrep_local_send_queue']
},
'percona_flow': {
'label': 'Flow control',
'vlabel': '',
'fields': ['wsrep_flow_control_sent', 'wsrep_flow_control_recv']
},
'percona_transactions': {
'label': 'Transactions in and out',
'vlabel': 'transactions',
'fields': ['wsrep_replicated', 'wsrep_received']
},
'percona_transactions_bytes': {
'label': 'Transactions in and out in bytes',
'vlabel': 'bytes',
'fields': ['wsrep_replicated_bytes', 'wsrep_received_bytes']
},
'percona_replication': {
'label': 'Replication conflicts',
'vlabel': 'conflicts',
'fields': ['wsrep_local_cert_failures', 'wsrep_local_bf_aborts'],
}
}
# Parse environment variables

View File

@ -139,8 +139,8 @@ def main():
telnet.write("server:uptime()\n")
telnet_response = telnet.read_until("minutes (", 5)
parsed_info = uptime_re.findall(telnet_response)
uptime_value = (float(parsed_info[0]) + float(parsed_info[1])/24
+ float(parsed_info[2])/60/24)
uptime_value = (float(parsed_info[0]) + float(parsed_info[1]) / 24
+ float(parsed_info[2]) / 60 / 24)
print("uptime.value %s" % (uptime_value))
telnet.write("quit\n")

View File

@ -102,7 +102,7 @@ def login(session, url, username, password):
bytes(password.encode("ascii")),
salt,
iterations=1000,
dklen=128/8
dklen=128 / 8
)
secret = {"Password": password, "Nonce": current_session_id}
plaintext = bytes(json.dumps(secret).encode("ascii"))

View File

@ -197,7 +197,7 @@ print(
"""multigraph technicolor_tc8715d_snr
graph_title Technicolor TC8715D Cable Modem SNR
graph_vlabel Signal-to-Noise Ratio (dB)
graph_info This graph shows the downstream signal-to-noise ratio reported by a Technicolor TC8715D cable modem.
graph_info Downstream signal-to-noise ratio reported by a Technicolor TC8715D cable modem.
graph_category network"""
)
@ -212,7 +212,7 @@ print(
"""multigraph technicolor_tc8715d_codewords
graph_title Technicolor TC8715D Cable Modem Codewords
graph_vlabel Codewords/${graph_period}
graph_info This graph shows the downstream codeword rates reported by a Technicolor TC8715D cable modem.
graph_info Downstream codeword rates reported by a Technicolor TC8715D cable modem.
graph_category network"""
)

View File

@ -77,7 +77,7 @@ def parse_params():
data = params['core'].rsplit('_', 1)
handler = data.pop()
params['params'] = {
'handler': os.environ.get('qpshandler_%s' % handler, 'standard')
'handler': os.environ.get('qpshandler_%s' % handler, 'standard'),
}
if not data:
params['core'] = ''
@ -416,7 +416,7 @@ class SolrMuninGraph:
handler=self.params['params']['handler'],
core=self.params['core'],
cores_qps_cdefs='%s,%s' % (','.join(map(lambda x: 'qps_%s' % x, cores)),
','.join(['+'] * (len(cores)-1))),
','.join(['+'] * (len(cores) - 1))),
gorder=','.join(cores)
)
@ -512,4 +512,4 @@ if __name__ == '__main__':
SOLR_URL = '/' + SOLR_URL
mb = SolrMuninGraph(SOLR_HOST_PORT, SOLR_URL, params)
if hasattr(mb, params['op']):
print(getattr(mb, params['op'])(params['type']))
print(getattr(mb, params['op'])(params['type']))

View File

@ -42,7 +42,7 @@ import sphinxsearch
prog_name = sys.argv[0]
index_name = prog_name[prog_name.find("_")+1:]
index_name = prog_name[prog_name.find("_") + 1:]
if len(sys.argv) == 2 and sys.argv[1] == "autoconf":
print("yes")

View File

@ -91,7 +91,7 @@ class SynologySNMPClient(object):
if not oid.startswith(disk_table):
continue
disk_id = oid[oid.rindex('.')+1:]
disk_id = oid[oid.rindex('.') + 1:]
values = devices.get(disk_id, [None, None, None])
if oid.startswith(disktable_id):
@ -119,21 +119,21 @@ class SynologySNMPClient(object):
return int(varBindTable[0][1])
def print_config(self):
print """multigraph synology_hdd_temperatures
print("""multigraph synology_hdd_temperatures
host_name {hostname}
graph_title HDD temperatures on {hostname}
graph_vlabel Temperature in °C
graph_args --base 1000
graph_category sensors
graph_info HDD temperatures on {hostname}""".format(hostname=self.hostname)
graph_info HDD temperatures on {hostname}""".format(hostname=self.hostname))
for id, name, model, temp in self._get_disks():
print """disk{disk_id}.info Temperature of {name} ({model})
print("""disk{disk_id}.info Temperature of {name} ({model})
disk{disk_id}.label {name} ({model})
disk{disk_id}.type GAUGE
disk{disk_id}.min 0""".format(disk_id=id, name=name, model=model)
disk{disk_id}.min 0""".format(disk_id=id, name=name, model=model))
print """multigraph synology_sys_temperature
print("""multigraph synology_sys_temperature
host_name {hostname}
graph_title System temperatures of {hostname}
graph_vlabel Temperature in °C
@ -144,15 +144,15 @@ sys_temp.info System temperature
sys_temp.label Temperature
sys_temp.type GAUGE
sys_temp.min 0
""".format(hostname=self.hostname)
""".format(hostname=self.hostname))
def execute(self):
print """multigraph synology_hdd_temperatures"""
print("""multigraph synology_hdd_temperatures""")
for id, name, model, temp in self._get_disks():
print """disk{disk_id}.value {temp}""".format(disk_id=id, temp=temp)
print("""disk{disk_id}.value {temp}""".format(disk_id=id, temp=temp))
print """multigraph synology_sys_temperature"""
print "sys_temp.value {temp}".format(temp=self._get_sys_temperature())
print("""multigraph synology_sys_temperature""")
print("sys_temp.value {temp}".format(temp=self._get_sys_temperature()))
host = None
@ -175,7 +175,7 @@ except Exception as ex:
if "snmpconf" in sys.argv[1:]:
print "require 1.3.6.1.4.1.6574.2.1.1"
print("require 1.3.6.1.4.1.6574.2.1.1")
sys.exit(0)
else:
if not (host and port and community):

View File

@ -121,25 +121,25 @@ log = logging.getLogger("delugeStats")
log.setLevel(logging.WARNING)
conf = {
'host': os.getenv('host', '127.0.0.1'),
'port': int(os.getenv('port', '58846')),
'username': os.getenv('username', ''),
'password': os.getenv('password', '')
'host': os.getenv('host', '127.0.0.1'),
'port': int(os.getenv('port', '58846')),
'username': os.getenv('username', ''),
'password': os.getenv('password', '')
}
names_for_munin = {
'numConnections': 'numConnections',
'payloadUploadRate': 'payloadUploadRate',
'overheadUploadRate': 'overheadUploadRate',
'payloadDownloadRate': 'payloadDownloadRate',
'overheadDownloadRate': 'overheadDownloadRate',
'state.Seeding': 'seeding',
'state.Downloading': 'downloading',
'state.Paused': 'paused',
'state.Error': 'error',
'state.Queued': 'queued',
'state.Checking': 'checking',
'state.Other': 'other'
'numConnections': 'numConnections',
'payloadUploadRate': 'payloadUploadRate',
'overheadUploadRate': 'overheadUploadRate',
'payloadDownloadRate': 'payloadDownloadRate',
'overheadDownloadRate': 'overheadDownloadRate',
'state.Seeding': 'seeding',
'state.Downloading': 'downloading',
'state.Paused': 'paused',
'state.Error': 'error',
'state.Queued': 'queued',
'state.Checking': 'checking',
'state.Other': 'other'
}
torrent_states = ["Downloading",
@ -300,8 +300,8 @@ def print_config(mode):
"graph_info This graph shows the number of connections used by Deluge Torrent")
print(names_for_munin["numConnections"] + ".label connections")
print(names_for_munin["numConnections"] + ".min 0")
print(names_for_munin["numConnections"] +
".info The number of connections used by Deluge Torrent")
print(names_for_munin["numConnections"]
+ ".info The number of connections used by Deluge Torrent")
elif mode == "bandwidth":
print("graph_title Bandwidth usage")
print("graph_order payloadDownloadRate overheadDownloadRate payloadUploadRate "
@ -353,13 +353,12 @@ def print_config(mode):
print("graph_period second")
for state_name in torrent_states:
print(names_for_munin["state." +
state_name] + ".label " + state_name)
print(names_for_munin["state." + state_name] + ".label " + state_name)
print(names_for_munin["state." + state_name] + ".draw AREASTACK")
print(names_for_munin["state." + state_name] + ".type GAUGE")
print(names_for_munin["state." + state_name] + ".min 0")
print(names_for_munin["state." + state_name] +
".info Number of torrents in the '" + state_name + "' state")
print(names_for_munin["state." + state_name]
+ ".info Number of torrents in the '" + state_name + "' state")
def fetch_info(mode):

View File

@ -3,7 +3,7 @@
import os
import re
import sys
import urllib
from urllib.request import urlopen
url = 'http://www.weather.com/weather/today/%s'
@ -19,7 +19,7 @@ if not code:
elif len(sys.argv) == 2 and sys.argv[1] == "autoconf":
print("yes")
elif len(sys.argv) == 2 and sys.argv[1] == "config":
u = urllib.urlopen(url % code)
u = urlopen(url % code)
txt = u.read()
u.close()
@ -39,7 +39,7 @@ elif len(sys.argv) == 2 and sys.argv[1] == "config":
print('graph_args --base 1000 -l 0')
else:
u = urllib.urlopen(url % code)
u = urlopen(url % code)
txt = u.read()
u.close()
@ -53,7 +53,7 @@ else:
if len(TMP_F_list):
TMP_F = TMP_F_list[0]
TMP_C = (int(TMP_F) - 32) * 5/9
TMP_C = (int(TMP_F) - 32) * 5 / 9
else:
sys.exit(1)

View File

@ -21,7 +21,7 @@ url = 'http://tgftp.nws.noaa.gov/data/observations/metar/decoded/%s.TXT'
re_hpa = re.compile(r'Pressure.*\((\d+) hPa\)')
code = sys.argv[0][(sys.argv[0].rfind('_')+1):]
code = sys.argv[0][(sys.argv[0].rfind('_') + 1):]
if not code:
sys.exit(1)
elif len(sys.argv) == 2 and sys.argv[1] == "autoconf":

View File

@ -21,7 +21,7 @@ url = 'http://tgftp.nws.noaa.gov/data/observations/metar/decoded/%s.TXT'
re_C = re.compile(r'Temperature:.*\((-?\d+\.?\d?) C\)')
re_DewC = re.compile(r'Dew.*\((-?\d+\.?\d?) C\)')
code = sys.argv[0][(sys.argv[0].rfind('_')+1):]
code = sys.argv[0][(sys.argv[0].rfind('_') + 1):]
if not code: