Skip to content

Commit 651d073

Browse files
authored
Merge pull request #2136 from sebix/pyupgrade36
ENH: upgrade Python syntax to 3.6+
2 parents dffed2d + ddc4d35 commit 651d073

File tree

88 files changed

+210
-244
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

88 files changed

+210
-244
lines changed

CHANGELOG.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<!-- comment
2-
SPDX-FileCopyrightText: 2015-2021 Sebastian Wagner
2+
SPDX-FileCopyrightText: 2015-2022 Sebastian Wagner
33
SPDX-License-Identifier: AGPL-3.0-or-later
44
-->
55

@@ -9,6 +9,8 @@ CHANGELOG
99
3.1.0 (unreleased)
1010
------------------
1111

12+
- Upgraded syntax to Python 3.6 (mostly Format-Strings) using pyuprade (PR#2136 by Sebastian Wagner).
13+
1214
### Configuration
1315

1416
### Core

contrib/check_mk/cronjob_intelmq_statistics.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,6 @@
3131
value = '0'
3232
else:
3333
value = value.decode()
34-
stats.append("%s=%s" % (key.decode(), value))
34+
stats.append(f"{key.decode()}={value}")
3535
handle.write("|".join(stats))
3636
handle.write('\n')

contrib/eventdb/apply_domain_suffix.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def eventdb_apply(host, port,
2020
table, dry_run, where,
2121
filename):
2222
if password:
23-
password = input('Password for user %r on %r: ' % (username, host))
23+
password = input(f'Password for user {username!r} on {host!r}: ')
2424
where = 'AND ' + where if where else ''
2525

2626
con1 = psycopg2.connect(user=username,

contrib/eventdb/apply_mapping_eventdb.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def eventdb_apply(malware_name_column, malware_family_column, host, port,
5050
print("Error: Python module 'psycopg2' is needed but not available.", file=sys.stderr)
5151
return 2
5252
if password:
53-
password = input('Password for user %r on %r: ' % (username, host))
53+
password = input(f'Password for user {username!r} on {host!r}: ')
5454
where = 'AND ' + where if where else ''
5555

5656
db = psycopg2.connect(database=database, user=username, password=password,

contrib/malware_name_mapping/download_mapping.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def none_len(arg: Optional[list]):
3838

3939

4040
def generate_rule(expression: str, identifier: str, name=None):
41-
return {"rulename": name if name else "%s-%s" % (identifier,
41+
return {"rulename": name if name else "{}-{}".format(identifier,
4242
hashlib.sha1(expression.encode()).hexdigest()[:10]),
4343
"if": {"classification.taxonomy": "malicious-code",
4444
"malware.name": expression
@@ -112,7 +112,7 @@ def download(url: str = URL, add_default=False, params=None, include_malpedia=Fa
112112
rules.append(generate_rule(".*", add_default, name="default"))
113113

114114
if params:
115-
rules.extend((generate_rule(rule[0][0], rule[1][0]) for rule in params))
115+
rules.extend(generate_rule(rule[0][0], rule[1][0]) for rule in params)
116116

117117
return json.dumps(rules, indent=4, separators=(',', ': '))
118118

docs/autogen.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def harm_docs():
7171

7272

7373
def info(key, value=""):
74-
return ("* **%s:** %s\n" % (key.title(), value)).strip() + '\n'
74+
return (f"* **{key.title()}:** {value}\n").strip() + '\n'
7575

7676

7777
def feeds_docs():
@@ -134,7 +134,7 @@ def feeds_docs():
134134
if isinstance(value, (list, tuple)) and value:
135135
value = json.dumps(value)
136136

137-
output += " * `%s`: `%s`\n" % (key, value)
137+
output += f" * `{key}`: `{value}`\n"
138138

139139
output += '\n'
140140

intelmq/bin/intelmq_generate_misp_objects_templates.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,11 +119,11 @@ def dump_templates(self):
119119

120120
objects = Path(args.objects)
121121
if not objects.exists():
122-
raise Exception('Path to misp-objects repository does not exists: {args.objects}'.format(args=args))
122+
raise Exception(f'Path to misp-objects repository does not exists: {args.objects}')
123123

124124
harmonization_file = Path(args.harmonization)
125125
if not harmonization_file.exists():
126-
raise Exception('Path to harmonization configuration does not exists: {args.harmonization}'.format(args=args))
126+
raise Exception(f'Path to harmonization configuration does not exists: {args.harmonization}')
127127

128128
g = MISPObjectTemplateGenerator(objects, harmonization_file)
129129
g.generate_templates()

intelmq/bin/intelmq_psql_initdb.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,9 @@ def generate(harmonization_file=HARMONIZATION_CONF_FILE):
2828

2929
try:
3030
print("INFO - Reading %s file" % harmonization_file)
31-
with open(harmonization_file, 'r') as fp:
31+
with open(harmonization_file) as fp:
3232
DATA = json.load(fp)['event']
33-
except IOError:
33+
except OSError:
3434
print("ERROR - Could not find %s" % harmonization_file)
3535
print("ERROR - Make sure that you have intelmq installed.")
3636
sys.exit(2)
@@ -69,7 +69,7 @@ def generate(harmonization_file=HARMONIZATION_CONF_FILE):
6969
initdb = """CREATE TABLE events (
7070
"id" BIGSERIAL UNIQUE PRIMARY KEY,"""
7171
for field, field_type in sorted(FIELDS.items()):
72-
initdb += '\n "{name}" {type},'.format(name=field, type=field_type)
72+
initdb += f'\n "{field}" {field_type},'
7373

7474
initdb = initdb[:-1] # remove last ','
7575
initdb += "\n);\n"
@@ -84,7 +84,7 @@ def main():
8484
fp = None
8585
try:
8686
if os.path.exists(OUTPUTFILE):
87-
print('INFO - File {} exists, generating temporary file.'.format(OUTPUTFILE))
87+
print(f'INFO - File {OUTPUTFILE} exists, generating temporary file.')
8888
os_fp, OUTPUTFILE = tempfile.mkstemp(suffix='.initdb.sql',
8989
text=True)
9090
fp = os.fdopen(os_fp, 'wt')

intelmq/bin/intelmqctl.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
psutil = None
4040

4141

42-
class Parameters(object):
42+
class Parameters:
4343
pass
4444

4545

@@ -206,7 +206,7 @@ def __init__(self, interactive: bool = False, returntype: ReturnType = ReturnTyp
206206
try:
207207
self._runtime_configuration = utils.load_configuration(RUNTIME_CONF_FILE)
208208
except ValueError as exc: # pragma: no cover
209-
self.abort('Error loading %r: %s' % (RUNTIME_CONF_FILE, exc))
209+
self.abort(f'Error loading {RUNTIME_CONF_FILE!r}: {exc}')
210210

211211
self._processmanagertype = getattr(self._parameters, 'process_manager', 'intelmq')
212212
if self._processmanagertype not in process_managers():
@@ -828,13 +828,13 @@ def check(self, no_connections=False):
828828
try:
829829
with open(HARMONIZATION_CONF_FILE) as file_handle:
830830
files[HARMONIZATION_CONF_FILE] = json.load(file_handle)
831-
except (IOError, ValueError) as exc: # pragma: no cover
831+
except (OSError, ValueError) as exc: # pragma: no cover
832832
check_logger.error('Could not load %r: %s.', HARMONIZATION_CONF_FILE, exc)
833833
retval = 1
834834
try:
835835
with open(RUNTIME_CONF_FILE) as file_handle:
836836
files[RUNTIME_CONF_FILE] = yaml.load(file_handle)
837-
except (IOError, ValueError) as exc:
837+
except (OSError, ValueError) as exc:
838838
check_logger.error('Could not load %r: %s.', RUNTIME_CONF_FILE, exc)
839839
retval = 1
840840
if retval:
@@ -933,7 +933,7 @@ def check(self, no_connections=False):
933933
bot_check = bot.check(bot_parameters)
934934
if bot_check:
935935
for log_line in bot_check:
936-
getattr(check_logger, log_line[0])("Bot %r: %s" % (bot_id, log_line[1]))
936+
getattr(check_logger, log_line[0])(f"Bot {bot_id!r}: {log_line[1]}")
937937
for group in utils.list_all_bots().values():
938938
for bot_id, bot in group.items():
939939
if subprocess.call(['which', bot['module']], stdout=subprocess.DEVNULL,
@@ -1026,7 +1026,7 @@ def upgrade_conf(self, previous=None, dry_run=None, function=None,
10261026
utils.write_configuration(state_file, state, new=True, useyaml=False)
10271027
except Exception as exc:
10281028
self._logger.error('Error writing state file %r: %s.', state_file, exc)
1029-
return 1, 'Error writing state file %r: %s.' % (state_file, exc)
1029+
return 1, f'Error writing state file {state_file!r}: {exc}.'
10301030
self._logger.info('Successfully wrote initial state file.')
10311031

10321032
runtime = utils.load_configuration(RUNTIME_CONF_FILE)
@@ -1241,7 +1241,7 @@ def debug(self, sections=None):
12411241
'CONFIG_DIR', 'ROOT_DIR'):
12421242
output['paths'][path] = variables[path]
12431243
if self._returntype is ReturnType.TEXT:
1244-
print('%s: %r' % (path, variables[path]))
1244+
print(f'{path}: {variables[path]!r}')
12451245
if sections is None or 'environment_variables' in sections:
12461246
output['environment_variables'] = {}
12471247
if self._returntype is ReturnType.TEXT:
@@ -1251,7 +1251,7 @@ def debug(self, sections=None):
12511251
'PATH'):
12521252
output['environment_variables'][variable] = os.getenv(variable)
12531253
if self._returntype is ReturnType.TEXT:
1254-
print('%s: %r' % (variable, os.getenv(variable)))
1254+
print(f'{variable}: {os.getenv(variable)!r}')
12551255
return 0, output
12561256

12571257
def log_bot_message(self, status, *args):

intelmq/bin/intelmqdump.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -92,24 +92,24 @@ def dump_info(fname, file_descriptor=None):
9292
else:
9393
try:
9494
if file_descriptor is None:
95-
handle = open(fname, 'rt')
95+
handle = open(fname)
9696
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
9797
else:
9898
handle = file_descriptor
9999
except BlockingIOError:
100100
info = red('Dump file is locked.')
101101
except OSError as exc:
102-
info = red('unable to open file: {!s}'.format(exc))
102+
info = red(f'unable to open file: {exc!s}')
103103
else:
104104
try:
105105
content = json.load(handle)
106106
except ValueError as exc:
107-
info = red('unable to load JSON: {!s}'.format(exc))
107+
info = red(f'unable to load JSON: {exc!s}')
108108
else:
109109
try:
110-
info = "{!s} dumps".format(len(content.keys()))
110+
info = f"{len(content.keys())!s} dumps"
111111
except AttributeError as exc:
112-
info = red("unable to count dumps: {!s}".format(exc))
112+
info = red(f"unable to count dumps: {exc!s}")
113113
finally:
114114
try:
115115
if file_descriptor is None:
@@ -221,7 +221,7 @@ def main():
221221
filenames = [(fname, fname[len(DEFAULT_LOGGING_PATH):-5])
222222
for fname in sorted(filenames)]
223223

224-
length = max([len(value[1]) for value in filenames])
224+
length = max(len(value[1]) for value in filenames)
225225
print(bold("{c:>3}: {s:{length}} {i}".format(c='id', s='name (bot id)',
226226
i='content',
227227
length=length)))
@@ -249,7 +249,7 @@ def main():
249249
fname = os.path.join(DEFAULT_LOGGING_PATH, botid) + '.dump'
250250

251251
if not os.path.isfile(fname):
252-
print(bold('Given file does not exist: {}'.format(fname)))
252+
print(bold(f'Given file does not exist: {fname}'))
253253
exit(1)
254254

255255
answer = None
@@ -264,7 +264,7 @@ def main():
264264
info = dump_info(fname, file_descriptor=handle)
265265
handle.seek(0)
266266
available_answers = ACTIONS.keys()
267-
print('Processing {}: {}'.format(bold(botid), info))
267+
print(f'Processing {bold(botid)}: {info}')
268268

269269
if info.startswith(str(red)):
270270
available_opts = [item[0] for item in ACTIONS.values() if item[2]]
@@ -351,7 +351,7 @@ def main():
351351
print('Event converted to Report automatically.')
352352
msg = message.Report(message.MessageFactory.unserialize(msg)).serialize()
353353
else:
354-
print(red("The given queue '{}' is not configured. Please retry with a valid queue.".format(queue_name)))
354+
print(red(f"The given queue '{queue_name}' is not configured. Please retry with a valid queue."))
355355
break
356356
try:
357357
pipe.set_queues(queue_name, 'destination')
@@ -362,12 +362,12 @@ def main():
362362
''.format(queue_name, traceback.format_exc())))
363363
else:
364364
del content[key]
365-
print(green('Recovered dump {}.'.format(i)))
365+
print(green(f'Recovered dump {i}.'))
366366
finally:
367367
save_file(handle, content)
368368
if not content:
369369
delete_file = True
370-
print('Deleting empty file {}'.format(fname))
370+
print(f'Deleting empty file {fname}')
371371
break
372372
elif answer[0] == 'd':
373373
# Delete entries or file
@@ -379,15 +379,15 @@ def main():
379379
else:
380380
# delete dumpfile
381381
delete_file = True
382-
print('Deleting file {}'.format(fname))
382+
print(f'Deleting file {fname}')
383383
break
384384
elif answer[0] == 's':
385385
# Show entries by id
386386
for count, (key, orig_value) in enumerate(content.items()):
387387
value = copy.copy(orig_value) # otherwise the raw field gets truncated
388388
if count not in ids:
389389
continue
390-
print('=' * 100, '\nShowing id {} {}\n'.format(count, key),
390+
print('=' * 100, f'\nShowing id {count} {key}\n',
391391
'-' * 50)
392392
if value.get('message_type') == 'base64':
393393
if args.truncate and len(value['message']) > args.truncate:

0 commit comments

Comments
 (0)