Skip to content

Commit 872cc3e

Browse files
authored
Fix all flake8 issues on python 3 (emscripten-core#9209)
1 parent 48551bb commit 872cc3e

24 files changed

+122
-120
lines changed

.flake8

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
[flake8]
2-
ignore = E111,E114,E501,E261,E266,E121,E402,E241
2+
ignore = E111,E114,E501,E261,E266,E121,E402,E241,W504
33
exclude =
44
./third_party/, # third-party code
55
./tools/filelock.py, # third-party code
66
./tools/scons/, # third-party code
77
./tests/freetype/src/, # third-party code
8+
./tests/poppler/poppler/, # third-party code
89
./site/source/conf.py,
910
./tools/debug/,
1011
./tools/emdump.py,

emar.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def run():
7878
newargs[j] = full_newname
7979
to_delete.append(full_newname)
8080
contents.add(newname)
81-
except:
81+
except Exception:
8282
# it is ok to fail here, we just don't get hashing
8383
contents.add(basename)
8484
pass

emcc.py

+18-17
Original file line numberDiff line numberDiff line change
@@ -503,7 +503,7 @@ def run(args):
503503
if '--version' in args:
504504
try:
505505
revision = run_process(['git', 'show'], stdout=PIPE, stderr=PIPE, cwd=shared.path_from_root()).stdout.splitlines()[0]
506-
except:
506+
except Exception:
507507
revision = '(unknown revision)'
508508
print('''emcc (Emscripten gcc/clang-like replacement) %s (%s)
509509
Copyright (C) 2014 the Emscripten authors (see AUTHORS.txt)
@@ -631,7 +631,7 @@ def is_minus_s_for_emcc(args, i):
631631
src = open(arg).read()
632632
if debug_configure:
633633
open(tempout, 'a').write('============= ' + arg + '\n' + src + '\n=============\n\n')
634-
except:
634+
except IOError:
635635
pass
636636
elif arg.endswith('.s'):
637637
if debug_configure:
@@ -721,7 +721,7 @@ def filter_emscripten_options(argv):
721721
open(target, 'w').write('#!' + full_node + '\n' + src) # add shebang
722722
try:
723723
os.chmod(target, stat.S_IMODE(os.stat(target).st_mode) | stat.S_IXUSR) # make executable
724-
except:
724+
except OSError:
725725
pass # can fail if e.g. writing the executable to /dev/null
726726
return ret
727727

@@ -862,7 +862,7 @@ def optimizing(opts):
862862
newargs[i] = newargs[i + 1] = ''
863863
if key == 'WASM_BACKEND=1':
864864
exit_with_error('do not set -s WASM_BACKEND, instead set EMCC_WASM_BACKEND=1 in the environment')
865-
newargs = [arg for arg in newargs if arg is not '']
865+
newargs = [arg for arg in newargs if arg != '']
866866

867867
settings_key_changes = set()
868868
for s in settings_changes:
@@ -929,14 +929,14 @@ def optimizing(opts):
929929
input_files.append((i, arg))
930930
elif file_suffix.endswith(STATICLIB_ENDINGS + DYNAMICLIB_ENDINGS):
931931
# if it's not, and it's a library, just add it to libs to find later
932-
l = unsuffixed_basename(arg)
932+
libname = unsuffixed_basename(arg)
933933
for prefix in LIB_PREFIXES:
934934
if not prefix:
935935
continue
936-
if l.startswith(prefix):
937-
l = l[len(prefix):]
936+
if libname.startswith(prefix):
937+
libname = libname[len(prefix):]
938938
break
939-
libs.append((i, l))
939+
libs.append((i, libname))
940940
newargs[i] = ''
941941
else:
942942
logger.warning(arg + ' is not a valid input file')
@@ -982,7 +982,7 @@ def optimizing(opts):
982982

983983
original_input_files = input_files[:]
984984

985-
newargs = [a for a in newargs if a is not '']
985+
newargs = [a for a in newargs if a != '']
986986

987987
has_dash_c = '-c' in newargs
988988
has_dash_S = '-S' in newargs
@@ -3122,7 +3122,7 @@ def generate_minimal_runtime_html(target, options, js_target, target_basename,
31223122
memfile, optimizer):
31233123
logger.debug('generating HTML for minimal runtime')
31243124
shell = read_and_preprocess(options.shell_path)
3125-
if re.search('{{{\s*SCRIPT\s*}}}', shell):
3125+
if re.search(r'{{{\s*SCRIPT\s*}}}', shell):
31263126
exit_with_error('--shell-file "' + options.shell_path + '": MINIMAL_RUNTIME uses a different kind of HTML page shell file than the traditional runtime! Please see $EMSCRIPTEN/src/shell_minimal_runtime.html for a template to use as a basis.')
31273127

31283128
shell = shell.replace('{{{ TARGET_BASENAME }}}', target_basename)
@@ -3528,7 +3528,7 @@ def parse_string_list(text):
35283528
# simpler syntaxes
35293529
try:
35303530
return json.loads(text)
3531-
except:
3531+
except ValueError:
35323532
return parse_string_list(text)
35333533

35343534
try:
@@ -3540,12 +3540,13 @@ def parse_string_list(text):
35403540
def validate_arg_level(level_string, max_level, err_msg, clamp=False):
35413541
try:
35423542
level = int(level_string)
3543-
if clamp:
3544-
if level > max_level:
3545-
logger.warning("optimization level '-O" + level_string + "' is not supported; using '-O" + str(max_level) + "' instead")
3546-
level = max_level
3547-
assert 0 <= level <= max_level
3548-
except:
3543+
except ValueError:
3544+
raise Exception(err_msg)
3545+
if clamp:
3546+
if level > max_level:
3547+
logger.warning("optimization level '-O" + level_string + "' is not supported; using '-O" + str(max_level) + "' instead")
3548+
level = max_level
3549+
if not 0 <= level <= max_level:
35493550
raise Exception(err_msg)
35503551
return level
35513552

emlink.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
def run():
1919
try:
2020
me, main, side, out = sys.argv[:4]
21-
except:
21+
except ValueError:
2222
print('usage: emlink.py [main module] [side module] [output name]', file=sys.stderr)
2323
sys.exit(1)
2424

emrun.py

+17-17
Original file line numberDiff line numberDiff line change
@@ -366,10 +366,10 @@ def kill_browser_process():
366366
else:
367367
try:
368368
subprocess.call(['pkill', processname_killed_atexit])
369-
except OSError as e:
369+
except OSError:
370370
try:
371371
subprocess.call(['killall', processname_killed_atexit])
372-
except OSError as e:
372+
except OSError:
373373
loge('Both commands pkill and killall failed to clean up the spawned browser process. Perhaps neither of these utilities is available on your system?')
374374
delete_emrun_safe_firefox_profile()
375375
# Clear the process name to represent that the browser is now dead.
@@ -567,7 +567,7 @@ def send_head(self):
567567

568568
def log_request(self, code):
569569
# Filter out 200 OK messages to remove noise.
570-
if code is not 200:
570+
if code != 200:
571571
SimpleHTTPRequestHandler.log_request(self, code)
572572

573573
def log_message(self, format, *args):
@@ -588,7 +588,7 @@ def do_POST(self):
588588
dump_out_directory = 'dump_out'
589589
try:
590590
os.mkdir(dump_out_directory)
591-
except:
591+
except OSError:
592592
pass
593593
filename = os.path.join(dump_out_directory, os.path.normpath(filename))
594594
open(filename, 'wb').write(data)
@@ -598,7 +598,7 @@ def do_POST(self):
598598
system_info = json.loads(get_system_info(format_json=True))
599599
try:
600600
browser_info = json.loads(get_browser_info(browser_exe, format_json=True))
601-
except:
601+
except ValueError:
602602
browser_info = ''
603603
data = {'system': system_info, 'browser': browser_info}
604604
self.send_response(200)
@@ -630,7 +630,7 @@ def do_POST(self):
630630
i = data.index('^', 5)
631631
seq_num = int(data[5:i])
632632
data = data[i + 1:]
633-
except:
633+
except ValueError:
634634
pass
635635

636636
is_exit = data.startswith('^exit^')
@@ -735,7 +735,7 @@ def find_gpu_model(model):
735735

736736
try:
737737
import_win32api_modules()
738-
except:
738+
except Exception:
739739
return []
740740

741741
for i in range(0, 16):
@@ -760,13 +760,13 @@ def find_gpu_model(model):
760760
try:
761761
driverVersion = winreg.QueryValueEx(hVideoCardReg, 'DriverVersion')[0]
762762
VideoCardDescription += ', driver version ' + driverVersion
763-
except:
763+
except WindowsError:
764764
pass
765765

766766
try:
767767
driverDate = winreg.QueryValueEx(hVideoCardReg, 'DriverDate')[0]
768768
VideoCardDescription += ' (' + driverDate + ')'
769-
except:
769+
except WindowsError:
770770
pass
771771

772772
VideoCardMemorySize = winreg.QueryValueEx(hVideoCardReg, 'HardwareInformation.MemorySize')[0]
@@ -831,7 +831,7 @@ def macos_get_gpu_info():
831831
memory = int(re.search("VRAM (.*?): (.*) MB", gpu).group(2).strip())
832832
gpus += [{'model': model_name + ' (' + bus + ')', 'ram': memory * 1024 * 1024}]
833833
return gpus
834-
except:
834+
except Exception:
835835
pass
836836

837837

@@ -941,7 +941,7 @@ def win_get_file_properties(fname):
941941
strInfo[propName] = win32api.GetFileVersionInfo(fname, strInfoPath)
942942

943943
props['StringFileInfo'] = strInfo
944-
except:
944+
except Exception:
945945
pass
946946

947947
return props
@@ -954,7 +954,7 @@ def get_computer_model():
954954
with open(os.path.join(os.getenv("HOME"), '.emrun.hwmodel.cached'), 'r') as f:
955955
model = f.read()
956956
return model
957-
except:
957+
except IOError:
958958
pass
959959

960960
try:
@@ -969,7 +969,7 @@ def get_computer_model():
969969
model = model.group(1).strip()
970970
open(os.path.join(os.getenv("HOME"), '.emrun.hwmodel.cached'), 'w').write(model) # Cache the hardware model to disk
971971
return model
972-
except:
972+
except Exception:
973973
hwmodel = check_output(['sysctl', 'hw.model'])
974974
hwmodel = re.search('hw.model: (.*)', hwmodel).group(1).strip()
975975
return hwmodel
@@ -1006,15 +1006,15 @@ def get_os_version():
10061006
version = ''
10071007
try:
10081008
version = ' ' + check_output(['wmic', 'os', 'get', 'version']).split('\n')[1].strip()
1009-
except:
1009+
except Exception:
10101010
pass
10111011
return productName[0] + version + bitness
10121012
elif MACOS:
10131013
return 'macOS ' + platform.mac_ver()[0] + bitness
10141014
elif LINUX:
10151015
kernel_version = check_output(['uname', '-r']).strip()
10161016
return ' '.join(platform.linux_distribution()) + ', linux kernel ' + kernel_version + ' ' + platform.architecture()[0] + bitness
1017-
except:
1017+
except Exception:
10181018
return 'Unknown OS'
10191019

10201020

@@ -1037,7 +1037,7 @@ def get_system_memory():
10371037
return win32api.GlobalMemoryStatusEx()['TotalPhys']
10381038
elif MACOS:
10391039
return int(check_output(['sysctl', '-n', 'hw.memsize']).strip())
1040-
except:
1040+
except Exception:
10411041
return -1
10421042

10431043

@@ -1292,7 +1292,7 @@ def get_system_info(format_json):
12921292
else:
12931293
try:
12941294
unique_system_id = open(os.path.expanduser('~/.emrun.generated.guid'), 'r').read().strip()
1295-
except:
1295+
except Exception:
12961296
import uuid
12971297
unique_system_id = str(uuid.uuid4())
12981298
try:

emscripten.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ def parse_fastcomp_output(backend_output, DEBUG):
145145

146146
try:
147147
metadata = json.loads(metadata_raw, object_pairs_hook=OrderedDict)
148-
except:
148+
except ValueError:
149149
logger.error('emscript: failure to parse metadata output from compiler backend. raw output is: \n' + metadata_raw)
150150
raise
151151

@@ -344,7 +344,7 @@ def move_preasm(m):
344344
# calculate globals
345345
try:
346346
del forwarded_json['Variables']['globals']['_llvm_global_ctors'] # not a true variable
347-
except:
347+
except KeyError:
348348
pass
349349
if not shared.Settings.RELOCATABLE:
350350
global_vars = metadata['externs']
@@ -450,7 +450,7 @@ def collapse_redundant_vars(code):
450450
old_code = ''
451451
while code != old_code: # Repeated vars overlap, so can't run in one regex pass. Runs in O(log(N)) time
452452
old_code = code
453-
code = re.sub('(var [^;]*);\s*var ', r'\1,\n ', code)
453+
code = re.sub(r'(var [^;]*);\s*var ', r'\1,\n ', code)
454454
return code
455455

456456

@@ -631,7 +631,7 @@ def is_int(x):
631631
try:
632632
int(x)
633633
return True
634-
except:
634+
except ValueError:
635635
return False
636636

637637

@@ -2211,7 +2211,7 @@ def emscript_wasm_backend(infile, outfile, memfile, libraries, compiler_engine,
22112211

22122212
try:
22132213
del forwarded_json['Variables']['globals']['_llvm_global_ctors'] # not a true variable
2214-
except:
2214+
except KeyError:
22152215
pass
22162216

22172217
sending = create_sending_wasm(invoke_funcs, forwarded_json, metadata)

site/source/get_api_items.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def addapiitems(matchobj):
4646
api_item = api_item.split('(')[0]
4747
try:
4848
api_item = api_item.split(' ')[1]
49-
except:
49+
except IndexError:
5050
pass
5151

5252
# print lang

site/source/get_wiki.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def errorhandler(func, path, exc_info):
5757
try:
5858
shutil.rmtree(output_dir, ignore_errors=False, onerror=errorhandler)
5959
print('Old wiki clone removed')
60-
except:
60+
except IOError:
6161
print('No directory to clean found')
6262

6363

@@ -72,7 +72,7 @@ def CloneWiki():
7272
try:
7373
os.makedirs(output_dir)
7474
print('Created directory')
75-
except:
75+
except OSError:
7676
pass
7777

7878
# Clone

tests/fuzz/creduce_tester.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def try_js(args):
5252
try:
5353
try_js(args)
5454
break
55-
except Exception as e:
55+
except Exception:
5656
pass
5757
else:
5858
sys.exit(0)

tests/fuzz/csmith_driver.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@
8282
shared.try_delete(filename)
8383
try:
8484
shared.run_process([COMP, '-m32', opts, fullname, '-o', filename + '1'] + CSMITH_CFLAGS + ['-w']) # + shared.EMSDK_OPTS
85-
except CalledProcessError as e:
85+
except CalledProcessError:
8686
print('Failed to compile natively using clang')
8787
notes['invalid'] += 1
8888
continue

tests/runner.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -630,7 +630,7 @@ def build(self, src, dirname, filename, main_file=None,
630630
try:
631631
# Make sure we notice if compilation steps failed
632632
os.remove(f + '.o')
633-
except:
633+
except OSError:
634634
pass
635635
args = [PYTHON, EMCC] + self.get_emcc_args(main_file=True) + \
636636
['-I' + dirname, '-I' + os.path.join(dirname, 'include')] + \
@@ -1653,7 +1653,7 @@ def build_library(name,
16531653
stderr = None
16541654
try:
16551655
Building.configure(configure + configure_args, env=env, stdout=stdout, stderr=stderr)
1656-
except subprocess.CalledProcessError as e:
1656+
except subprocess.CalledProcessError:
16571657
pass # Ignore exit code != 0
16581658

16591659
def open_make_out(mode='r'):
@@ -1758,7 +1758,7 @@ def skip_requested_tests(args, modules):
17581758
suite = getattr(m, suite_name)
17591759
setattr(suite, test_name, lambda s: s.skipTest("requested to be skipped"))
17601760
break
1761-
except:
1761+
except AttributeError:
17621762
pass
17631763
args[i] = None
17641764
return [a for a in args if a is not None]

0 commit comments

Comments
 (0)