diff --git a/em-config b/em-config index 785b04e5a553..0e61e0132523 100755 --- a/em-config +++ b/em-config @@ -11,14 +11,15 @@ This tool prints the value of the variable to stdout if one is found, or exits with 1 if the variable does not exist. ''' +from __future__ import print_function import os, sys, re from tools import shared if len(sys.argv) != 2 or \ not re.match(r"^[\w\W_][\w\W_\d]*$", sys.argv[1]) or \ not (sys.argv[1] in dir(shared)): - print 'Usage: em-config VAR_NAME' + print('Usage: em-config VAR_NAME') exit(1) -print eval('shared.' + sys.argv[1]) +print(eval('shared.' + sys.argv[1])) diff --git a/emar.py b/emar.py index 842a75076df3..bc8f28c85e35 100755 --- a/emar.py +++ b/emar.py @@ -7,6 +7,7 @@ This script acts as a frontend replacement for ar. See emcc. ''' +from __future__ import print_function from tools.toolchain_profiler import ToolchainProfiler if __name__ == '__main__': ToolchainProfiler.record_process_start() @@ -25,7 +26,7 @@ def run(): newargs = [shared.LLVM_AR] + sys.argv[1:] if DEBUG: - print >> sys.stderr, 'emar:', sys.argv, ' ==> ', newargs + print('emar:', sys.argv, ' ==> ', newargs, file=sys.stderr) if len(newargs) > 2: to_delete = [] diff --git a/embuilder.py b/embuilder.py index 52cd12d25692..0a0528c8b96e 100755 --- a/embuilder.py +++ b/embuilder.py @@ -4,11 +4,12 @@ Tool to manage building of various useful things, such as libc, libc++, native optimizer, as well as fetch and build ports like zlib and sdl2 ''' +from __future__ import print_function import os, sys import tools.shared as shared if len(sys.argv) < 2 or sys.argv[1] in ['-v', '-help', '--help', '-?', '?']: - print ''' + print(''' Emscripten System Builder Tool ============================== @@ -60,7 +61,7 @@ and set up the location to the native optimizer in ~/.emscripten -''' +''') sys.exit(0) C_BARE = ''' @@ -127,12 +128,12 @@ def build_port(port_name, lib_name, params): tasks = [x for x in tasks if x not in skip_tasks] else: if os.environ.get('EMSCRIPTEN_NATIVE_OPTIMIZER'): - print 'Skipping building of native-optimizer since environment variable EMSCRIPTEN_NATIVE_OPTIMIZER is present and set to point to a prebuilt native optimizer path.' + print('Skipping building of native-optimizer since environment variable EMSCRIPTEN_NATIVE_OPTIMIZER is present and set to point to a prebuilt native optimizer path.') elif hasattr(shared, 'EMSCRIPTEN_NATIVE_OPTIMIZER'): - print 'Skipping building of native-optimizer since .emscripten config file has set EMSCRIPTEN_NATIVE_OPTIMIZER to point to a prebuilt native optimizer path.' + print('Skipping building of native-optimizer since .emscripten config file has set EMSCRIPTEN_NATIVE_OPTIMIZER to point to a prebuilt native optimizer path.') else: tasks += ['native_optimizer'] - print 'Building targets: %s' % ' '.join (tasks) + print('Building targets: %s' % ' '.join(tasks)) for what in tasks: shared.logging.info('building and verifying ' + what) if what == 'compiler-rt': diff --git a/emcc.py b/emcc.py index a2bc79c7848c..db7767efe7fa 100755 --- a/emcc.py +++ b/emcc.py @@ -23,6 +23,7 @@ EMMAKEN_COMPILER - The compiler to be used, if you don't want the default clang. ''' +from __future__ import print_function from tools.toolchain_profiler import ToolchainProfiler, exit if __name__ == '__main__': ToolchainProfiler.record_process_start() @@ -328,13 +329,13 @@ def run(): # An online HTML version (which may be of a different version of Emscripten) # is up at http://kripken.github.io/emscripten-site/docs/tools_reference/emcc.html - print '''%s + print('''%s ------------------------------------------------------------------ emcc: supported targets: llvm bitcode, javascript, NOT elf (autoconf likes to see elf above to enable shared object support) -''' % (open(shared.path_from_root('site', 'build', 'text', 'docs', 'tools_reference', 'emcc.txt')).read()) +''' % (open(shared.path_from_root('site', 'build', 'text', 'docs', 'tools_reference', 'emcc.txt')).read())) exit(0) elif sys.argv[1] == '--version': @@ -347,22 +348,22 @@ def run(): pass finally: os.chdir(here) - print '''emcc (Emscripten gcc/clang-like replacement) %s (%s) + print('''emcc (Emscripten gcc/clang-like replacement) %s (%s) Copyright (C) 2014 the Emscripten authors (see AUTHORS.txt) This is free and open source software under the MIT license. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - ''' % (shared.EMSCRIPTEN_VERSION, revision) + ''' % (shared.EMSCRIPTEN_VERSION, revision)) exit(0) elif len(sys.argv) == 2 and sys.argv[1] == '-v': # -v with no inputs # autoconf likes to see 'GNU' in the output to enable shared object support - print 'emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) %s' % shared.EMSCRIPTEN_VERSION + print('emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) %s' % shared.EMSCRIPTEN_VERSION) code = subprocess.call([shared.CLANG, '-v']) shared.check_sanity(force=True) exit(code) elif '-dumpmachine' in sys.argv: - print shared.get_llvm_target() + print(shared.get_llvm_target()) exit(0) elif '--cflags' in sys.argv: @@ -377,7 +378,7 @@ def run(): line = re.search('running: (.*)', lines[0]).group(1) parts = shlex.split(line.replace('\\', '\\\\')) parts = filter(lambda x: x != '-c' and x != '-o' and input_file not in x and temp_target not in x and '-emit-llvm' not in x, parts) - print ' '.join(shared.Building.doublequote_spaces(parts[1:])) + print(' '.join(shared.Building.doublequote_spaces(parts[1:]))) exit(0) def is_minus_s_for_emcc(newargs, i): @@ -879,7 +880,7 @@ def check(input_file): value = '"' + value + '"' else: value = value.replace('\\', '\\\\') - exec 'shared.Settings.' + key + ' = ' + value in globals(), locals() + exec('shared.Settings.' + key + ' = ' + value, globals(), locals()) if key == 'EXPORTED_FUNCTIONS': # used for warnings in emscripten.py shared.Settings.ORIGINAL_EXPORTED_FUNCTIONS = original_exported_response or shared.Settings.EXPORTED_FUNCTIONS[:] @@ -2189,7 +2190,7 @@ def separate_asm_js(final, asm_target): # extra only-my-code logic if shared.Settings.ONLY_MY_CODE: temp = asm_target + '.only.js' - print jsrun.run_js(shared.path_from_root('tools', 'js-optimizer.js'), shared.NODE_JS, args=[asm_target, 'eliminateDeadGlobals', 'last', 'asm'], stdout=open(temp, 'w')) + print(jsrun.run_js(shared.path_from_root('tools', 'js-optimizer.js'), shared.NODE_JS, args=[asm_target, 'eliminateDeadGlobals', 'last', 'asm'], stdout=open(temp, 'w'))) shutil.move(temp, asm_target) diff --git a/emconfigure.py b/emconfigure.py index 29bbabe92a70..293659fd0392 100755 --- a/emconfigure.py +++ b/emconfigure.py @@ -17,6 +17,7 @@ CONFIGURE_CC - see emcc ''' +from __future__ import print_function import os, sys from tools import shared from subprocess import CalledProcessError @@ -26,7 +27,7 @@ # def run(): if len(sys.argv) < 2 or ('configure' not in sys.argv[1] and 'cmake' not in sys.argv[1]): - print >> sys.stderr, ''' + print(''' emconfigure is a helper for configure, setting various environment variables so that emcc etc. are used. Typical usage: @@ -34,7 +35,7 @@ def run(): (but you can run any command instead of configure) - ''' + ''', file=sys.stderr) elif 'cmake' in sys.argv[1]: node_js = shared.NODE_JS if type(node_js) is list: node_js = node_js[0] diff --git a/emlink.py b/emlink.py index f767ce583a03..15bce23cabb7 100755 --- a/emlink.py +++ b/emlink.py @@ -6,6 +6,7 @@ See https://github.com/kripken/emscripten/wiki/Linking ''' +from __future__ import print_function import sys from tools import shared from tools.asm_module import AsmModule @@ -14,12 +15,12 @@ def run(): try: me, main, side, out = sys.argv[:4] except: - print >> sys.stderr, 'usage: emlink.py [main module] [side module] [output name]' + print('usage: emlink.py [main module] [side module] [output name]', file=sys.stderr) sys.exit(1) - print 'Main module:', main - print 'Side module:', side - print 'Output:', out + print('Main module:', main) + print('Side module:', side) + print('Output:', out) shared.try_delete(out) diff --git a/emmake.py b/emmake.py index 0cd88d173efb..a02faf398acd 100755 --- a/emmake.py +++ b/emmake.py @@ -18,6 +18,7 @@ generate JavaScript. ''' +from __future__ import print_function import os, sys from tools import shared from subprocess import CalledProcessError @@ -27,7 +28,7 @@ # def run(): if len(sys.argv) < 2 or sys.argv[1] != 'make': - print >> sys.stderr, ''' + print(''' emmake is a helper for make, setting various environment variables so that emcc etc. are used. Typical usage: @@ -35,7 +36,7 @@ def run(): (but you can run any command instead of make) - ''' + ''', file=sys.stderr) try: shared.Building.make(sys.argv[1:]) diff --git a/tools/asm_module.py b/tools/asm_module.py index b5eaef3e9367..1e45fc52ce81 100644 --- a/tools/asm_module.py +++ b/tools/asm_module.py @@ -1,4 +1,5 @@ +from __future__ import print_function import sys, re, itertools import shared, js_optimizer @@ -138,7 +139,7 @@ def relocate_into(self, main): def check_import(key, value): if value.startswith('+') or value.endswith('|0'): # ignore functions if key not in all_sendings: - print >> sys.stderr, 'warning: external variable %s is still not defined after linking' % key + print('warning: external variable %s is still not defined after linking' % key, file=sys.stderr) all_sendings[key] = '0' for key, value in all_imports.iteritems(): check_import(key, value) diff --git a/tools/autodebugger.py b/tools/autodebugger.py index faf2e7607277..26bcebcb6fc9 100644 --- a/tools/autodebugger.py +++ b/tools/autodebugger.py @@ -8,6 +8,7 @@ there may be weird errors. ''' +from __future__ import print_function import os, sys, re ALLOW_POINTERS = True @@ -264,5 +265,5 @@ f.write(ll[:meta_start] + '\n' + POSTAMBLE + '\n' + ll[meta_start:]) f.close() -print 'Success.' +print('Success.') diff --git a/tools/autodebugger_c.py b/tools/autodebugger_c.py index 54a4d6910cbe..16567527a412 100644 --- a/tools/autodebugger_c.py +++ b/tools/autodebugger_c.py @@ -5,11 +5,12 @@ overwrite the files it is given! ''' +from __future__ import print_function import os, sys, re filenames = sys.argv[1:] for filename in filenames: - print '..%s..' % filename + print('..%s..' % filename) f = open(filename, 'r') data = f.read() @@ -33,5 +34,5 @@ f.write('\n'.join(lines)) f.close() -print 'Success.' +print('Success.') diff --git a/tools/autodebugger_indenter.py b/tools/autodebugger_indenter.py index 7c1de6649290..50d9a062cdcf 100644 --- a/tools/autodebugger_indenter.py +++ b/tools/autodebugger_indenter.py @@ -3,6 +3,7 @@ This script will indent the output nicely ''' +from __future__ import print_function import os, sys lines = sys.stdin.read().split('\n') @@ -12,7 +13,7 @@ line = lines[i] if line.startswith('AD:-2,'): depth -= 1 - print str(depth) + '|' + line + print(str(depth) + '|' + line) if line.startswith('AD:-1,'): depth += 1 diff --git a/tools/autodebugger_js.py b/tools/autodebugger_js.py index a054dead5628..3bd7ee43953b 100644 --- a/tools/autodebugger_js.py +++ b/tools/autodebugger_js.py @@ -4,6 +4,7 @@ Similar to autodebugger.py, but runs on .js files. ''' +from __future__ import print_function import os, sys, re filename = sys.argv[1] @@ -41,7 +42,7 @@ left, right = lines[i].split(' = ') lines[i] += ''' print("%s = " + %s);''' % (left, left) -print '\n'.join(lines) +print('\n'.join(lines)) -print >> sys.stderr, 'Success.' +print('Success.', file=sys.stderr) diff --git a/tools/autodediffer.py b/tools/autodediffer.py index 68ecf821c3f7..0a539ae24be6 100644 --- a/tools/autodediffer.py +++ b/tools/autodediffer.py @@ -4,6 +4,7 @@ Run it with filenames of two autodebugger logs as parameters ''' +from __future__ import print_function import os, sys @@ -54,7 +55,7 @@ def process_line(line): assert av[0] == bv[0] diff = abs(av[1] - bv[1]) if diff > MIN: - print '<<%d %d>> %d : %.5f' % (ai, bi, av[0], diff) + print('<<%d %d>> %d : %.5f' % (ai, bi, av[0], diff)) ai += 1 bi += 1 diff --git a/tools/bindings_generator.py b/tools/bindings_generator.py index 9bc8b9295aa3..6f8a7dd8da3c 100755 --- a/tools/bindings_generator.py +++ b/tools/bindings_generator.py @@ -123,6 +123,7 @@ when compiling in asm.js mode. ''' +from __future__ import print_function import os, sys, glob, re __rootpath__ = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -155,7 +156,7 @@ def path_from_root(*pathelems): if json.get('export'): export = json['export'] - print 'zz ignoring', ignored + print('zz ignoring', ignored) # First pass - read everything @@ -172,9 +173,9 @@ def path_from_root(*pathelems): all_h.close() parsed = CppHeaderParser.CppHeader(all_h_name) -print 'zz dir: ', parsed.__dict__.keys() +print('zz dir: ', parsed.__dict__.keys()) for classname, clazz in parsed.classes.items() + parsed.structs.items(): - print 'zz see', classname, clazz, type(clazz) + print('zz see', classname, clazz, type(clazz)) classes[classname] = clazz if type(clazz['methods']) == dict: clazz['saved_methods'] = clazz['methods'] @@ -189,14 +190,14 @@ def path_from_root(*pathelems): parents[sname] = classname classes[classname + '::' + sname] = struct struct['name'] = sname # Missing in CppHeaderParser - print 'zz seen struct %s in %s' % (sname, classname) + print('zz seen struct %s in %s' % (sname, classname)) if 'fields' in clazz: # This is a struct - print 'zz add properties!' + print('zz add properties!') clazz['properties'] = { 'public': clazz['fields'] } clazz['name'] = classname clazz['inherits'] = [] -print 'zz parents: ', parents +print('zz parents: ', parents) def check_has_constructor(clazz): for method in clazz['methods']: @@ -205,10 +206,10 @@ def check_has_constructor(clazz): for classname, clazz in parsed.classes.items() + parsed.structs.items(): # Various precalculations - print 'zz precalc', classname + print('zz precalc', classname) for method in clazz['methods'][:]: method['constructor'] = method['constructor'] or (method['name'] == classname) # work around cppheaderparser issue - print 'z constructorhmm?', method['name'], method['constructor']#, constructor, method['name'], classname + print('z constructorhmm?', method['name'], method['constructor'])#, constructor, method['name'], classname args = method['parameters'] #if method['name'] == 'addWheel': print 'qqqq', classname, method @@ -230,7 +231,7 @@ def check_has_constructor(clazz): break method['parameters'] = [args[:i] for i in range(default_param-1, len(args)+1)] - print 'zz ', classname, 'has parameters in range', range(default_param-1, len(args)+1) + print('zz ', classname, 'has parameters in range', range(default_param-1, len(args)+1)) method['returns_text'] = method['returns'] if method['static']: @@ -245,7 +246,7 @@ def check_has_constructor(clazz): method['name'] = 'op_add' method['operator'] = ' return *self += arg0;' elif 'sub' in method['name']: - print 'zz subsubsub ', classname, method['name'], method['parameters'][0] + print('zz subsubsub ', classname, method['name'], method['parameters'][0]) method['name'] = 'op_sub' if len(method['parameters'][0]) == 0: method['operator'] = ' static %s ret; ret = -*self; return ret;' % method['returns'] @@ -271,7 +272,7 @@ def check_has_constructor(clazz): method['name'] = 'op_comp' method['operator'] = ' return arg0 == arg1;' if len(method['parameters'][0]) == 2 else ' return *self == arg0;' else: - print 'zz unknown operator:', method['name'], ', ignoring' + print('zz unknown operator:', method['name'], ', ignoring') method['ignore'] = True # Fill in some missing stuff @@ -291,11 +292,11 @@ def check_has_constructor(clazz): for prop in clazz['properties']['public']: if classname + '::' + prop['name'] in ignored: continue if prop.get('array_dimensions'): - print 'zz warning: ignoring getter/setter for array', classname + '::' + prop['name'] + print('zz warning: ignoring getter/setter for array', classname + '::' + prop['name']) continue type_ = prop['type'].replace('mutable ', '')#.replace(' ', '') if '<' in prop['name'] or '<' in type_: - print 'zz warning: ignoring getter/setter for templated class', classname + '::' + prop['name'] + print('zz warning: ignoring getter/setter for templated class', classname + '::' + prop['name']) continue reference = type_ in classes # a raw struct or class as a prop means we need to work with a ref clazz['methods'].append({ @@ -328,14 +329,14 @@ def check_has_constructor(clazz): }]], }) - print 'zz is effectively abstract?', clazz['name'], classname, '0' + print('zz is effectively abstract?', clazz['name'], classname, '0') if 'saved_methods' in clazz and not check_has_constructor(clazz): - print 'zz is effectively abstract?', clazz['name'], '1' + print('zz is effectively abstract?', clazz['name'], '1') # Having a private constructor and no public constructor means you are, in effect, abstract for private_method in clazz['saved_methods']['private']: - print 'zz is effectively abstract?', clazz['name'], '2' + print('zz is effectively abstract?', clazz['name'], '2') if private_method['constructor']: - print 'zz is effectively abstract?', clazz['name'], '3' + print('zz is effectively abstract?', clazz['name'], '3') clazz['effectively_abstract'] = True # Add destroyer @@ -384,18 +385,18 @@ def copy_args(args): def explore(subclass, template_name=None, template_value=None): # Do our functions first, and do not let later classes override for method in subclass['methods']: - print classname, 'exploring', subclass['name'], '::', method['name'] + print(classname, 'exploring', subclass['name'], '::', method['name']) if method['constructor']: if clazz != subclass: - print "zz Subclasses cannot directly use their parent's constructors" + print("zz Subclasses cannot directly use their parent's constructors") continue if method['destructor']: - print 'zz Nothing to do there' + print('zz Nothing to do there') continue if method.get('operator') and subclass is not clazz: - print 'zz Do not use parent class operators. Cast to that class if you need those operators (castObject)' + print('zz Do not use parent class operators. Cast to that class if you need those operators (castObject)') continue if method['name'] not in clazz['final_methods']: @@ -430,13 +431,13 @@ def explore(subclass, template_name=None, template_value=None): if len(curr_args) == len(method_args): problem = True if problem: - print 'Warning: Cannot mix in overloaded functions', method['name'], 'in class', classname, ', skipping' + print('Warning: Cannot mix in overloaded functions', method['name'], 'in class', classname, ', skipping') continue # TODO: Other compatibility checks, if any? curr['parameters'] += map(copy_args, method['parameters']) - print 'zz ', classname, 'has updated parameters of ', curr['parameters'] + print('zz ', classname, 'has updated parameters of ', curr['parameters']) # Recurse if subclass.get('inherits'): @@ -448,11 +449,11 @@ def explore(subclass, template_name=None, template_value=None): parent, template = parent.split('<') template_name = classes[parent]['template_typename'] template_value = fix_template_value(template.replace('>', '')) - print 'template', template_value, 'for', classname, '::', parent, ' | ', template_name + print('template', template_value, 'for', classname, '::', parent, ' | ', template_name) if parent not in classes and '::' in classname: # They might both be subclasses in the same parent parent = classname.split('::')[0] + '::' + parent if parent not in classes: - print 'Warning: parent class', parent, 'not a known class. Ignoring.' + print('Warning: parent class', parent, 'not a known class. Ignoring.') return explore(classes[parent], template_name, template_value) @@ -596,7 +597,7 @@ def generate_wrapping_code(classname): # %(classname)s.prototype['fields'] = Runtime.generateStructInfo(null, '%(classname)s'); - consider adding this def generate_class(generating_classname, classname, clazz): # TODO: deprecate generating? - print 'zz generating:', generating_classname, classname + print('zz generating:', generating_classname, classname) generating_classname_head = generating_classname.split('::')[-1] classname_head = classname.split('::')[-1] @@ -610,11 +611,11 @@ def generate_class(generating_classname, classname, clazz): # TODO: deprecate ge gen_js.write('''Module['%s'] = %s; ''' % (generating_classname_head, generating_classname_head)) - print 'zz methods: ', clazz['final_methods'].keys() + print('zz methods: ', clazz['final_methods'].keys()) for method in clazz['final_methods'].itervalues(): mname = method['name'] if classname_head + '::' + mname in ignored: - print 'zz ignoring', mname + print('zz ignoring', mname) continue params = method['parameters'] @@ -622,7 +623,7 @@ def generate_class(generating_classname, classname, clazz): # TODO: deprecate ge destructor = method['destructor'] static = method['static'] - print 'zz generating %s::%s' % (generating_classname, method['name']) + print('zz generating %s::%s' % (generating_classname, method['name'])) if destructor: continue if constructor and inherited: continue @@ -759,7 +760,7 @@ def dummyargs(args): ''' % (fullname, i, ', '.join(justargs_fixed[:i])) else: return_value = '''_%s_p%d(%s)''' % (fullname, i, ', '.join((['this.ptr'] if need_self else []) + justargs_fixed[:i])) - print 'zz making return', classname, method['name'], method['returns'], return_value + print('zz making return', classname, method['name'], method['returns'], return_value) if method['returns'] in classes: # Generate a wrapper calls += '''return wrapPointer(%s, Module['%s']);''' % (return_value, method['returns'].split('::')[-1]) @@ -771,7 +772,7 @@ def dummyargs(args): if has_string_convs: calls = 'var stack = Runtime.stackSave();\ntry {\n' + calls + '} finally { Runtime.stackRestore(stack) }\n'; - print 'Maekin:', classname, generating_classname, mname, mname_suffixed + print('Maekin:', classname, generating_classname, mname, mname_suffixed) if constructor: calls += ''' %s.prototype.__cache__[this.ptr] = this; @@ -809,11 +810,11 @@ def dummyargs(args): for classname, clazz in parsed.classes.items() + parsed.structs.items(): if any([name in ignored for name in classname.split('::')]): - print 'zz ignoring', classname + print('zz ignoring', classname) continue if clazz.get('template_typename'): - print 'zz ignoring templated base class', classname + print('zz ignoring templated base class', classname) continue # Nothing to generate for pure virtual classes XXX actually this is not so. We do need to generate wrappers for returned objects, @@ -823,13 +824,13 @@ def dummyargs(args): def check_pure_virtual(clazz, progeny): #if not clazz.get('inherits'): return False # If no inheritance info, not a class, this is a CppHeaderParser struct - print 'Checking pure virtual for', clazz['name'], clazz['inherits'] + print('Checking pure virtual for', clazz['name'], clazz['inherits']) # If we do not recognize any of the parent classes, assume this is pure virtual - ignore it parents = [parent['class'] for parent in clazz['inherits']] parents = [parent.split('<')[0] for parent in parents] # remove template stuff parents = [parent if parent in classes else possible_prefix + parent for parent in parents] if any([not parent in classes for parent in parents]): - print 'zz Warning: unknown parent class', parents, 'for', classname + print('zz Warning: unknown parent class', parents, 'for', classname) return True if any([check_pure_virtual(classes[parent], [clazz] + progeny) for parent in parents]): return True @@ -845,23 +846,23 @@ def dirtied(mname): for method in clazz['methods']: if method['pure_virtual'] and not dirtied(method['name']): - print 'zz ignoring pure virtual class', classname, 'due to', method['name'] + print('zz ignoring pure virtual class', classname, 'due to', method['name']) return True clazz['abstract'] = check_pure_virtual(clazz, []) or clazz.get('effectively_abstract') - print 'zz', classname, 'is abstract?', clazz['abstract'] + print('zz', classname, 'is abstract?', clazz['abstract']) #if check_pure_virtual(clazz, []): # continue # Add a constructor if none exist has_constructor = check_has_constructor(clazz) - print 'zz', classname, 'has constructor?', has_constructor + print('zz', classname, 'has constructor?', has_constructor) if not has_constructor: if not clazz['abstract']: - print 'zz no constructor for', classname, 'and not abstract, so ignoring' + print('zz no constructor for', classname, 'and not abstract, so ignoring') continue #clazz['methods'] = [{ diff --git a/tools/bisect_pair.py b/tools/bisect_pair.py index 133dd9d1f7bd..2fb61a2277b9 100644 --- a/tools/bisect_pair.py +++ b/tools/bisect_pair.py @@ -4,6 +4,7 @@ diff that makes the outputs different. ''' +from __future__ import print_function import os, sys, shutil from subprocess import Popen, PIPE, STDOUT @@ -29,13 +30,13 @@ def run_code(name): ret = filter(lambda line: not line.startswith(' at ') and not name in line, ret.split('\n')) return '\n'.join(ret) -print 'running files' +print('running files') left_result = run_code('left') right_result = run_code('right') # right as in left-right, not as in correct assert left_result != right_result # Calculate diff chunks -print 'diffing' +print('diffing') diff = Popen(['diff', '-U', '5', 'left', 'right'], stdout=PIPE).communicate()[0].split('\n') pre_diff = diff[:2] diff = diff[2:] @@ -55,10 +56,10 @@ def run_code(name): # Bisect both sides of the span, until we have a single chunk high = len(chunks) -print 'beginning bisection, %d chunks' % high +print('beginning bisection, %d chunks' % high) for mid in range(high): - print ' current: %d' % mid, + print(' current: %d' % mid, end=' ') # Take chunks from the middle and on. This is important because the eliminator removes variables, so starting from the beginning will add errors curr_diff = '\n'.join(map(lambda parts: '\n'.join(parts), chunks[mid:])) + '\n' difff = open('diff.diff', 'w') @@ -68,15 +69,15 @@ def run_code(name): Popen(['patch', 'middle', 'diff.diff'], stdout=PIPE).communicate() shutil.copyfile('middle', 'middle' + str(mid)) result = run_code('middle') - print result == left_result, result == right_result#, 'XXX', left_result, 'YYY', result, 'ZZZ', right_result + print(result == left_result, result == right_result)#, 'XXX', left_result, 'YYY', result, 'ZZZ', right_result if mid == 0: assert result == right_result, '<<< ' + result + ' ??? ' + right_result + ' >>>' - print 'sanity check passed (a)' + print('sanity check passed (a)') if mid == high-1: assert result == left_result, '<<< ' + result + ' ??? ' + left_result + ' >>>' - print 'sanity check passed (b)' + print('sanity check passed (b)') if result != right_result: - print 'found where it changes: %d' % mid + print('found where it changes: %d' % mid) found = mid break @@ -84,5 +85,5 @@ def run_code(name): c = open('critical.diff', 'w') c.write(critical) c.close() -print 'middle%d is like left, middle%d is like right, critical.diff is the difference that matters' % (mid-1, mid), 'diff:', critical +print('middle%d is like left, middle%d is like right, critical.diff is the difference that matters' % (mid-1, mid), 'diff:', critical) diff --git a/tools/bisect_pair_lines.py b/tools/bisect_pair_lines.py index f698ef2a7475..1b744578ad98 100644 --- a/tools/bisect_pair_lines.py +++ b/tools/bisect_pair_lines.py @@ -6,6 +6,7 @@ the programs differ on each line but lines have not been added or removed ''' +from __future__ import print_function import os, sys, shutil from subprocess import Popen, PIPE, STDOUT @@ -31,7 +32,7 @@ def run_code(name): ret = filter(lambda line: not line.startswith(' at ') and not name in line, ret.split('\n')) return '\n'.join(ret) -print 'running files' +print('running files') left_result = run_code('left') right_result = run_code('right') # right as in left-right, not as in correct assert left_result != right_result @@ -39,18 +40,18 @@ def run_code(name): low = 0 high = file1.count('\n') -print 'beginning bisection, %d lines' % high +print('beginning bisection, %d lines' % high) left_lines = file1.split('\n') right_lines = file2.split('\n') while True: mid = int((low + high)/2) - print low, high, ' current: %d' % mid, + print(low, high, ' current: %d' % mid, end=' ') open('middle', 'w').write('\n'.join(left_lines[:mid] + right_lines[mid:])) shutil.copyfile('middle', 'middle' + str(mid)) result = run_code('middle') - print result == left_result, result == right_result#, 'XXX', left_result, 'YYY', result, 'ZZZ', right_result + print(result == left_result, result == right_result)#, 'XXX', left_result, 'YYY', result, 'ZZZ', right_result if mid == low or mid == high: break if result == right_result: low = mid @@ -59,5 +60,5 @@ def run_code(name): else: raise Exception('new result!?!?') -print 'middle%d is like left, middle%d is like right' % (mid+1, mid) +print('middle%d is like left, middle%d is like right' % (mid+1, mid)) diff --git a/tools/bisect_pair_wast.py b/tools/bisect_pair_wast.py index 6de3238b835d..6bfc00c26831 100644 --- a/tools/bisect_pair_wast.py +++ b/tools/bisect_pair_wast.py @@ -4,6 +4,7 @@ diff that makes the outputs different. ''' +from __future__ import print_function import os, sys, shutil from subprocess import Popen, PIPE, STDOUT @@ -30,13 +31,13 @@ def run_code(name): ret = filter(lambda line: not line.startswith(' at ') and not name in line, ret.split('\n')) return '\n'.join(ret) -print 'running files' +print('running files') left_result = run_code('left') right_result = run_code('right') # right as in left-right, not as in correct assert left_result != right_result # Calculate diff chunks -print 'diffing' +print('diffing') diff = Popen(['diff', '-U', '5', 'left', 'right'], stdout=PIPE).communicate()[0].split('\n') pre_diff = diff[:2] diff = diff[2:] @@ -56,10 +57,10 @@ def run_code(name): # Bisect both sides of the span, until we have a single chunk high = len(chunks) -print 'beginning bisection, %d chunks' % high +print('beginning bisection, %d chunks' % high) for mid in range(high): - print ' current: %d' % mid, + print(' current: %d' % mid, end=' ') # Take chunks from the middle and on. This is important because the eliminator removes variables, so starting from the beginning will add errors curr_diff = '\n'.join(map(lambda parts: '\n'.join(parts), chunks[mid:])) + '\n' difff = open('diff.diff', 'w') @@ -69,15 +70,15 @@ def run_code(name): Popen(['patch', 'middle', 'diff.diff'], stdout=PIPE).communicate() shutil.copyfile('middle', 'middle' + str(mid)) result = run_code('middle') - print result == left_result, result == right_result#, 'XXX', left_result, 'YYY', result, 'ZZZ', right_result + print(result == left_result, result == right_result)#, 'XXX', left_result, 'YYY', result, 'ZZZ', right_result if mid == 0: assert result == right_result, '<<< ' + result + ' ??? ' + right_result + ' >>>' - print 'sanity check passed (a)' + print('sanity check passed (a)') if mid == high-1: assert result == left_result, '<<< ' + result + ' ??? ' + left_result + ' >>>' - print 'sanity check passed (b)' + print('sanity check passed (b)') if result != right_result: - print 'found where it changes: %d' % mid + print('found where it changes: %d' % mid) found = mid break @@ -85,5 +86,5 @@ def run_code(name): c = open('critical.diff', 'w') c.write(critical) c.close() -print 'middle%d is like left, middle%d is like right, critical.diff is the difference that matters' % (mid-1, mid), 'diff:', critical +print('middle%d is like left, middle%d is like right, critical.diff is the difference that matters' % (mid-1, mid), 'diff:', critical) diff --git a/tools/cache.py b/tools/cache.py index 8c6ba0ef42d7..c4e17644c3e7 100644 --- a/tools/cache.py +++ b/tools/cache.py @@ -1,3 +1,4 @@ +from __future__ import print_function from toolchain_profiler import ToolchainProfiler import os.path, sys, shutil, time, logging import tempfiles, filelock @@ -73,7 +74,7 @@ def erase(self): try: open(self.dirname + '__last_clear', 'w').write('last clear: ' + time.asctime() + '\n') except Exception, e: - print >> sys.stderr, 'failed to save last clear time: ', e + print('failed to save last clear time: ', e, file=sys.stderr) self.filelock = None tempfiles.try_delete(self.filelock_name) self.filelock = filelock.FileLock(self.filelock_name) diff --git a/tools/clean_webconsole.py b/tools/clean_webconsole.py index 43694179d071..c61147b96376 100644 --- a/tools/clean_webconsole.py +++ b/tools/clean_webconsole.py @@ -2,6 +2,7 @@ Removes timestamp and line info from a webgl log ''' +from __future__ import print_function import os, sys, re __rootpath__ = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -27,7 +28,7 @@ def nice(x): line = line[15:] line = line.split(' @ ')[0] line = re.sub('(0x[\dabcdef]+)', lambda hexx: reps[nice(hexx.group(0))] if nice(hexx.group(0)) in reps else nice(hexx.group(0)), line) - print line + print(line) #for i in range(100): # print diff --git a/tools/create_dom_pk_codes.py b/tools/create_dom_pk_codes.py index 5f7daf9ebf83..85371bdf00e4 100644 --- a/tools/create_dom_pk_codes.py +++ b/tools/create_dom_pk_codes.py @@ -24,6 +24,7 @@ # Use #include in your code to access these IDs. +from __future__ import print_function import sys, random input_strings = [ @@ -220,9 +221,9 @@ def hash_all(k1, k2): str_to_hash = {} for s in input_strings: h = hash(s[1], k1, k2) - print >> sys.stderr, 'String "' + s[1] + '" hashes to %s ' % hex(h) + print('String "' + s[1] + '" hashes to %s ' % hex(h), file=sys.stderr) if h in hashes: - print >> sys.stderr, 'Collision! Earlier string ' + hashes[h] + ' also hashed to %s!' % hex(h) + print('Collision! Earlier string ' + hashes[h] + ' also hashed to %s!' % hex(h), file=sys.stderr) return None else: hashes[h] = s[1] @@ -242,8 +243,8 @@ def hash_all(k1, k2): perfect_hash_table = hash_all(k1, k2) hash_to_str, str_to_hash = perfect_hash_table -print >> sys.stderr, 'Found collision-free hash function!' -print >> sys.stderr, 'h_i = ((h_(i-1) ^ %s) << %s) ^ s_i' % (hex(k1), hex(k2)) +print('Found collision-free hash function!', file=sys.stderr) +print('h_i = ((h_(i-1) ^ %s) << %s) ^ s_i' % (hex(k1), hex(k2)), file=sys.stderr) def pad_to_length(s, length): return s + max(0, length - len(s)) * ' ' diff --git a/tools/diff_autodebugger.py b/tools/diff_autodebugger.py index 0a2a7634f65b..481ee1cab2cb 100644 --- a/tools/diff_autodebugger.py +++ b/tools/diff_autodebugger.py @@ -2,6 +2,7 @@ Very simple line-by line diff of autodebugger outputs. useful when there are no added or removed lines, and there are float differences ''' +from __future__ import print_function import os, sys f1 = open(sys.argv[1], 'r').readlines() @@ -11,5 +12,5 @@ if f1[i] == f2[i]: continue v1 = float(f1[i].split(',')[1]) v2 = float(f2[i].split(',')[1]) - print '%5d %10s %f ' % (i+1, f1[i].split(',')[0], v1-v2), ' ', v1-v2, v1, v2 + print('%5d %10s %f ' % (i+1, f1[i].split(',')[0], v1-v2), ' ', v1-v2, v1, v2) diff --git a/tools/duplicate_function_eliminator.py b/tools/duplicate_function_eliminator.py index c8b28da988cb..c6eebdfa4645 100644 --- a/tools/duplicate_function_eliminator.py +++ b/tools/duplicate_function_eliminator.py @@ -1,4 +1,5 @@ +from __future__ import print_function import os, sys, subprocess, multiprocessing, re, string, json, shutil, logging, traceback import shared from js_optimizer import * @@ -36,10 +37,10 @@ def run_on_chunk(command): if os.environ.get('EMCC_SAVE_OPT_TEMP') and os.environ.get('EMCC_SAVE_OPT_TEMP') != '0': saved = 'save_' + os.path.basename(filename) while os.path.exists(saved): saved = 'input' + str(int(saved.replace('input', '').replace('.txt', ''))+1) + '.txt' - print >> sys.stderr, 'running DFE command', ' '.join(map(lambda c: c if c != filename else saved, command)) + print('running DFE command', ' '.join(map(lambda c: c if c != filename else saved, command)), file=sys.stderr) shutil.copyfile(filename, os.path.join(shared.get_emscripten_temp_dir(), saved)) - if shared.EM_BUILD_VERBOSE_LEVEL >= 3: print >> sys.stderr, 'run_on_chunk: ' + str(command) + if shared.EM_BUILD_VERBOSE_LEVEL >= 3: print('run_on_chunk: ' + str(command), file=sys.stderr) proc = subprocess.Popen(command, stdout=subprocess.PIPE) output = proc.communicate()[0] @@ -52,7 +53,7 @@ def run_on_chunk(command): f = open(filename, 'wb') f.write(output) f.close() - if DEBUG and not shared.WINDOWS: print >> sys.stderr, '.' # Skip debug progress indicator on Windows, since it doesn't buffer well with multiple threads printing to console. + if DEBUG and not shared.WINDOWS: print('.', file=sys.stderr) # Skip debug progress indicator on Windows, since it doesn't buffer well with multiple threads printing to console. return filename except KeyboardInterrupt: # avoid throwing keyboard interrupts from a child process @@ -60,10 +61,10 @@ def run_on_chunk(command): except (TypeError, ValueError) as e: formatted_lines = traceback.format_exc().splitlines() - print >> sys.stderr, ">>>>>>>>>>>>>>>>>" + print(">>>>>>>>>>>>>>>>>", file=sys.stderr) for formatted_line in formatted_lines: - print >> sys.stderr, formatted_line - print >> sys.stderr, "<<<<<<<<<<<<<<<<<" + print(formatted_line, file=sys.stderr) + print("<<<<<<<<<<<<<<<<<", file=sys.stderr) raise @@ -75,11 +76,11 @@ def dump_equivalent_functions(passed_in_filename, global_data): # If we are running more than one pass, then we want to merge # all the hash infos into one if os.path.isfile(equivalent_fn_json_file): - print >> sys.stderr, "Merging data from current pass for {} into {}".format(passed_in_filename, equivalent_fn_json_file) + print("Merging data from current pass for {} into {}".format(passed_in_filename, equivalent_fn_json_file), file=sys.stderr) with open(equivalent_fn_json_file) as data_file: equivalent_fn_info = json.load(data_file) else: - print >> sys.stderr, "Writing equivalent functions for {} to {}".format(passed_in_filename, equivalent_fn_json_file) + print("Writing equivalent functions for {} to {}".format(passed_in_filename, equivalent_fn_json_file), file=sys.stderr) # Merge the global data's fn_hash_to_fn_name structure into # the equivalent function info hash. @@ -222,7 +223,7 @@ def run_on_js(filename, gen_hash_info=False): chunks = shared.chunkify(funcs, chunk_size) chunks = filter(lambda chunk: len(chunk) > 0, chunks) - if DEBUG and len(chunks) > 0: print >> sys.stderr, 'chunkification: num funcs:', len(funcs), 'actual num chunks:', len(chunks), 'chunk size range:', max(map(len, chunks)), '-', min(map(len, chunks)) + if DEBUG and len(chunks) > 0: print('chunkification: num funcs:', len(funcs), 'actual num chunks:', len(chunks), 'chunk size range:', max(map(len, chunks)), '-', min(map(len, chunks)), file=sys.stderr) funcs = None if len(chunks) > 0: @@ -245,17 +246,17 @@ def write_chunk(chunk, i): commands = map(lambda filename: js_engine + [DUPLICATE_FUNCTION_ELIMINATOR, filename, '--gen-hash-info' if gen_hash_info else '--use-hash-info', '--no-minimize-whitespace'], filenames) if DEBUG and commands is not None: - print >> sys.stderr, [' '.join(command if command is not None else '(null)') for command in commands] + print([' '.join(command if command is not None else '(null)') for command in commands], file=sys.stderr) cores = min(cores, len(filenames)) if len(chunks) > 1 and cores >= 2: # We can parallelize - if DEBUG: print >> sys.stderr, 'splitting up js optimization into %d chunks, using %d cores (total: %.2f MB)' % (len(chunks), cores, total_size/(1024*1024.)) + if DEBUG: print('splitting up js optimization into %d chunks, using %d cores (total: %.2f MB)' % (len(chunks), cores, total_size/(1024*1024.)), file=sys.stderr) pool = shared.Building.get_multiprocessing_pool() filenames = pool.map(run_on_chunk, commands, chunksize=1) else: # We can't parallize, but still break into chunks to avoid uglify/node memory issues - if len(chunks) > 1 and DEBUG: print >> sys.stderr, 'splitting up js optimization into %d chunks' % (len(chunks)) + if len(chunks) > 1 and DEBUG: print('splitting up js optimization into %d chunks' % (len(chunks)), file=sys.stderr) filenames = [run_on_chunk(command) for command in commands] else: filenames = [] @@ -316,7 +317,7 @@ def save_temp_file(file_to_process): if not os.path.exists(os.path.dirname(destinationFile)): os.makedirs(os.path.dirname(destinationFile)) - print >> sys.stderr, "Copying {} to {}".format(file_to_process, destinationFile) + print("Copying {} to {}".format(file_to_process, destinationFile), file=sys.stderr) shutil.copyfile(file_to_process, destinationFile) def get_func_names(javascript_file): @@ -342,13 +343,13 @@ def eliminate_duplicate_funcs(file_name): # Remove previous log file if it exists equivalent_fn_json_file = file_name + ".equivalent_functions.json" if os.path.isfile(equivalent_fn_json_file): - print >> sys.stderr, "Deleting old json: " + equivalent_fn_json_file + print("Deleting old json: " + equivalent_fn_json_file, file=sys.stderr) os.remove(equivalent_fn_json_file) old_funcs = get_func_names(file_name) for pass_num in range(shared.Settings.ELIMINATE_DUPLICATE_FUNCTIONS_PASSES): - if DEBUG: print >> sys.stderr, "[PASS {}]: eliminating duplicate functions in: {}.".format(pass_num, file_name) + if DEBUG: print("[PASS {}]: eliminating duplicate functions in: {}.".format(pass_num, file_name), file=sys.stderr) # Generate the JSON for the equivalent hash first processed_file = run_on_js(filename=file_name, gen_hash_info=True) @@ -367,7 +368,7 @@ def eliminate_duplicate_funcs(file_name): new_funcs = get_func_names(file_name) eliminated_funcs_file = file_name + ".eliminated_functions.json" - print >> sys.stderr, "Writing eliminated functions to file: {}".format(eliminated_funcs_file) + print("Writing eliminated functions to file: {}".format(eliminated_funcs_file), file=sys.stderr) with open(eliminated_funcs_file, 'w') as fout: eliminated_functions = list(set(old_funcs)-set(new_funcs)) diff --git a/tools/emconfiguren.py b/tools/emconfiguren.py index 35d83b87c328..1c4fc203659d 100755 --- a/tools/emconfiguren.py +++ b/tools/emconfiguren.py @@ -1,7 +1,8 @@ #!/usr/bin/env python2 +from __future__ import print_function import sys -print >> sys.stderr, '\n\nemconfiguren.py is deprecated! use "emconfigure"\n\n' +print('\n\nemconfiguren.py is deprecated! use "emconfigure"\n\n', file=sys.stderr) ''' This is a helper script for emmaken.py. See docs in that file for more info. diff --git a/tools/emmaken.py b/tools/emmaken.py index 44707f5b71aa..16f91fcf63ec 100755 --- a/tools/emmaken.py +++ b/tools/emmaken.py @@ -1,7 +1,8 @@ #!/usr/bin/env python2 +from __future__ import print_function import sys -print >> sys.stderr, '\n\nemmaken.py is deprecated! use "emcc"\n\n' +print('\n\nemmaken.py is deprecated! use "emcc"\n\n', file=sys.stderr) ''' emmaken - the emscripten make proxy tool @@ -98,7 +99,7 @@ def path_from_root(*pathelems): import os import subprocess -print >> sys.stderr, 'emmaken.py: ', ' '.join(sys.argv) +print('emmaken.py: ', ' '.join(sys.argv), file=sys.stderr) __rootpath__ = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def path_from_root(*pathelems): @@ -112,7 +113,7 @@ def path_from_root(*pathelems): if CONFIGURE_CONFIG or CMAKE_CONFIG: compiler = 'g++' if 'CXXCompiler' in ' '.join(sys.argv) or os.environ.get('EMMAKEN_CXX') else 'gcc' cmd = [compiler] + EMSDK_OPTS + sys.argv[1:] - print >> sys.stderr, 'emmaken.py, just configuring: ', cmd + print('emmaken.py, just configuring: ', cmd, file=sys.stderr) exit(subprocess.call(cmd)) try: @@ -206,14 +207,14 @@ def path_from_root(*pathelems): newargs = sys.argv[1:] for i in range(len(newargs)): if newargs[i].startswith('-O'): - print >> sys.stderr, 'emmaken.py: WARNING: Optimization flags (-Ox) are ignored in emmaken. Tell emscripten.py to do that, or run LLVM opt.' + print('emmaken.py: WARNING: Optimization flags (-Ox) are ignored in emmaken. Tell emscripten.py to do that, or run LLVM opt.', file=sys.stderr) newargs[i] = '' newargs = [ arg for arg in newargs if arg is not '' ] + CC_ADDITIONAL_ARGS newargs.append('-emit-llvm') if not use_linker: newargs.append('-c') else: - print >> sys.stderr, 'Just copy.' + print('Just copy.', file=sys.stderr) shutil.copy(sys.argv[-1], sys.argv[-2]) exit(0) @@ -221,10 +222,10 @@ def path_from_root(*pathelems): #f.write('Calling: ' + ' '.join(newargs) + '\n\n') #f.close() - print >> sys.stderr, "Running:", call, ' '.join(newargs) + print("Running:", call, ' '.join(newargs), file=sys.stderr) subprocess.call([call] + newargs) except Exception, e: - print 'Error in emmaken.py. (Is the config file %s set up properly?) Error:' % EM_CONFIG, e + print('Error in emmaken.py. (Is the config file %s set up properly?) Error:' % EM_CONFIG, e) raise diff --git a/tools/emprofile.py b/tools/emprofile.py index 1803e36ee959..f32f4ddb3f57 100755 --- a/tools/emprofile.py +++ b/tools/emprofile.py @@ -1,5 +1,6 @@ #!/usr/bin/env python +from __future__ import print_function import sys, shutil, os, json, tempfile, time profiler_logs_path = os.path.join(tempfile.gettempdir(), 'emscripten_toolchain_profiler_logs') @@ -36,7 +37,7 @@ def create_profiling_graph(): all_results = [] if len(log_files) > 0: - print 'Processing ' + str(len(log_files)) + ' profile log files in "' + profiler_logs_path + '"...' + print('Processing ' + str(len(log_files)) + ' profile log files in "' + profiler_logs_path + '"...') for f in log_files: try: json_data = open(f, 'r').read() @@ -47,29 +48,29 @@ def create_profiling_graph(): json_data = '[' + '\n'.join(lines) + ']' all_results += json.loads(json_data) except Exception, e: - print >> sys.stderr, str(e) - print >> sys.stderr, 'Failed to parse JSON file "' + f + '"!' + print(str(e), file=sys.stderr) + print('Failed to parse JSON file "' + f + '"!', file=sys.stderr) sys.exit(1) if len(all_results) == 0: - print 'No profiler logs were found in path "' + profiler_logs_path + '". Try setting the environment variable EM_PROFILE_TOOLCHAIN=1 and run some emcc commands, and then rerun "python emprofile.py --graph" again.' + print('No profiler logs were found in path "' + profiler_logs_path + '". Try setting the environment variable EM_PROFILE_TOOLCHAIN=1 and run some emcc commands, and then rerun "python emprofile.py --graph" again.') return all_results.sort(key=lambda x: x['time']) json_file = OUTFILE + '.json' open(json_file, 'w').write(json.dumps(all_results, indent=2)) - print 'Wrote "' + json_file + '"' + print('Wrote "' + json_file + '"') html_file = OUTFILE + '.html' html_contents = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'toolchain_profiler.results_template.html'), 'r').read().replace('{{{results_log_file}}}', '"' + json_file + '"') open(html_file, 'w').write(html_contents) - print 'Wrote "' + html_file + '"' + print('Wrote "' + html_file + '"') if not DEBUG_EMPROFILE_PY: delete_profiler_logs() if len(sys.argv) < 2: - print '''Usage: + print('''Usage: emprofile.py --reset Deletes all previously recorded profiling log files. @@ -80,7 +81,7 @@ def create_profiling_graph(): --outfile=x.html Specifies the name of the results file to generate. -''' +''') sys.exit(1) if '--reset' in sys.argv: @@ -88,5 +89,5 @@ def create_profiling_graph(): elif '--graph' in sys.argv: create_profiling_graph() else: - print 'Unknown command "' + sys.argv[1] + '"!' + print('Unknown command "' + sys.argv[1] + '"!') sys.exit(1) diff --git a/tools/emterpretify.py b/tools/emterpretify.py index e06fad392b54..619368fc9627 100755 --- a/tools/emterpretify.py +++ b/tools/emterpretify.py @@ -6,6 +6,7 @@ Currently this requires the asm.js code to have been built with -s FINALIZE_ASM_JS=0 ''' +from __future__ import print_function import os, sys, re, json import asm_module, shared, shutil @@ -48,7 +49,7 @@ def handle_arg(arg): temp_files = config.get_temp_files() if DEBUG: - print >> sys.stderr, 'running emterpretify on', sys.argv + print('running emterpretify on', sys.argv, file=sys.stderr) if FROUND: shared.Settings.PRECISE_F32 = 1 @@ -241,7 +242,7 @@ def randomize_opcodes(): global OPCODES import random random.shuffle(opcodes) - print OPCODES + print(OPCODES) #randomize_opcodes() assert len(OPCODES) == len(set(OPCODES)) # no dupe names @@ -724,9 +725,9 @@ def process(code): data = shared.Building.calculate_reachable_functions(infile, list(SYNC_FUNCS)) advised = data['reachable'] total_funcs = data['total_funcs'] - print "Suggested list of functions to run in the emterpreter:" - print " -s EMTERPRETIFY_WHITELIST='" + str(sorted(advised)).replace("'", '"') + "'" - print "(%d%% out of %d functions)" % (int((100.0*len(advised))/total_funcs), total_funcs) + print("Suggested list of functions to run in the emterpreter:") + print(" -s EMTERPRETIFY_WHITELIST='" + str(sorted(advised)).replace("'", '"') + "'") + print("(%d%% out of %d functions)" % (int((100.0*len(advised))/total_funcs), total_funcs)) sys.exit(0) # final global functions @@ -889,11 +890,11 @@ def process_code(func, code, absolute_targets): try: func, curr, absolute_targets = json.loads(line[len('// EMTERPRET_INFO '):]) except Exception, e: - print >> sys.stderr, 'failed to parse code from', line + print('failed to parse code from', line, file=sys.stderr) raise e assert len(curr) % 4 == 0, len(curr) funcs[func] = len(all_code) # no operation here should change the length - if LOG_CODE: print >> sys.stderr, 'raw bytecode for %s:' % func, curr, 'insts:', len(curr)/4 + if LOG_CODE: print('raw bytecode for %s:' % func, curr, 'insts:', len(curr)/4, file=sys.stderr) process_code(func, curr, absolute_targets) #print >> sys.stderr, 'processed bytecode for %s:' % func, curr all_code += curr diff --git a/tools/ffdb.py b/tools/ffdb.py index f40b868e4f7b..abd72f4c7ac1 100755 --- a/tools/ffdb.py +++ b/tools/ffdb.py @@ -1,5 +1,6 @@ #!/usr/bin/env python +from __future__ import print_function import socket, json, sys, uuid, datetime, time, logging, cgi, zipfile, os, tempfile, atexit, subprocess, re, base64, struct, imghdr WINDOWS = sys.platform == 'win32' @@ -43,11 +44,11 @@ def zipdir(path, zipfilename): filename = os.path.join(root, file) filesize = os.path.getsize(filename) path_in_archive = os.path.relpath(filename, path) - print 'Compressing ' + str(n) + '/' + str(len(files_to_compress)) + ': "' + path_in_archive + '" (' + sizeof_fmt(filesize) + ')...' + print('Compressing ' + str(n) + '/' + str(len(files_to_compress)) + ': "' + path_in_archive + '" (' + sizeof_fmt(filesize) + ')...') n += 1 zipf.write(os.path.join(root, file), path_in_archive) zipf.close() - print 'Done. ' + print('Done. ') # Returns given log message formatted to be outputted on a HTML page. def format_html(msg): @@ -85,10 +86,10 @@ def read_b2g_response(print_errors_to_console = True): pass # We simulate blocking sockets with looping over reads that time out, since on Windows, the user cannot press Ctrl-C to break on blocking sockets. except Exception, e: if e[0] == 57: # Socket is not connected - print 'Error! Failed to receive data from the device: socket is not connected!' + print('Error! Failed to receive data from the device: socket is not connected!') sys.exit(1) else: - print 'Got exception ' + str(e) + print('Got exception ' + str(e)) raise continue payload = read_queue[semicolon+1:semicolon+1+payload_len] @@ -97,7 +98,7 @@ def read_b2g_response(print_errors_to_console = True): payload = json.loads(payload) # Log received errors immediately to console if print_errors_to_console and 'error' in payload: - print >> sys.stderr, 'Received error "' + payload['error'] + '"! Reason: ' + payload['message'] + print('Received error "' + payload['error'] + '"! Reason: ' + payload['message'], file=sys.stderr) else: break return payload @@ -169,7 +170,7 @@ def print_applist(applist, running_app_manifests, print_removable): version = '' if app['manifestURL'] in running_app_manifests: version += ' RUNNING' - print ' ' + str(app['localId']) + ': "' + app['name'] + '"' + version + print(' ' + str(app['localId']) + ': "' + app['name'] + '"' + version) num_printed += 1 return num_printed @@ -195,7 +196,7 @@ def b2g_get_pref(sub): for line in prefs_data: m = r.match(line) if m and (sub is None or sub in m.group(1)): - print m.group(1) + ': ' + m.group(2).strip() + print(m.group(1) + ': ' + m.group(2).strip()) def b2g_set_pref(pref, value): prefs_data = b2g_get_prefs_data().split('\n') @@ -208,10 +209,10 @@ def b2g_set_pref(pref, value): new_prefs_data += [line] if value != None: - print 'Setting pref "' + pref + '" = ' + value + print('Setting pref "' + pref + '" = ' + value) new_prefs_data += ['user_pref("' + pref + '", ' + value + ');'] else: - print 'Unsetting pref "' + pref + '"' + print('Unsetting pref "' + pref + '"') (oshandle, tempfilename) = tempfile.mkstemp(suffix='.js', prefix='ffdb_temp_') os.write(oshandle, '\n'.join(new_prefs_data)); @@ -219,7 +220,7 @@ def b2g_set_pref(pref, value): subprocess.check_output([ADB, 'shell', 'stop', 'b2g']) subprocess.check_output([ADB, 'push', tempfilename, b2g_get_prefs_filename()]) subprocess.check_output([ADB, 'shell', 'start', 'b2g']) - print 'Rebooting phone...' + print('Rebooting phone...') def delete_temp_file(): os.remove(tempfilename) @@ -229,7 +230,7 @@ def get_packaged_app_manifest(target_app_path): if os.path.isdir(target_app_path): manifest_file = os.path.join(target_app_path, 'manifest.webapp') if not os.path.isfile(manifest_file): - print "Error: Failed to find FFOS packaged app manifest file '" + manifest_file + "'! That directory does not contain a packaged app?" + print("Error: Failed to find FFOS packaged app manifest file '" + manifest_file + "'! That directory does not contain a packaged app?") sys.exit(1) return json.loads(open(manifest_file, 'r').read()) elif target_app_path.endswith('.zip') and os.path.isfile(target_app_path): @@ -237,18 +238,18 @@ def get_packaged_app_manifest(target_app_path): z = zipfile.ZipFile(target_app_path, "r") bytes = z.read('manifest.webapp') except Exception, e: - print "Error: Failed to read FFOS packaged app manifest file 'manifest.webapp' in zip file '" + target_app_path + "'! Error: " + str(e) + print("Error: Failed to read FFOS packaged app manifest file 'manifest.webapp' in zip file '" + target_app_path + "'! Error: " + str(e)) sys.exit(1) return None return json.loads(str(bytes)) else: - print "Error: Path '" + target_app_path + "' is neither a directory or a .zip file to represent the location of a FFOS packaged app!" + print("Error: Path '" + target_app_path + "' is neither a directory or a .zip file to represent the location of a FFOS packaged app!") sys.exit(1) return None def b2g_install(target_app_path): if os.path.isdir(target_app_path): - print 'Zipping up the contents of directory "' + target_app_path + '"...' + print('Zipping up the contents of directory "' + target_app_path + '"...') (oshandle, tempzip) = tempfile.mkstemp(suffix='.zip', prefix='ffdb_temp_') zipdir(target_app_path, tempzip) target_app_path = tempzip @@ -257,8 +258,8 @@ def delete_temp_file(): os.remove(tempzip) atexit.register(delete_temp_file) - print 'Uploading application package "' + target_app_path + '"...' - print 'Size of compressed package: ' + sizeof_fmt(os.path.getsize(target_app_path)) + '.' + print('Uploading application package "' + target_app_path + '"...') + print('Size of compressed package: ' + sizeof_fmt(os.path.getsize(target_app_path)) + '.') app_file = open(target_app_path, 'rb') data = app_file.read() file_size = len(data) @@ -269,7 +270,7 @@ def delete_temp_file(): packageUploadActor = uploadResponse['actor'] send_b2g_bulk_data(packageUploadActor, data) else: # Old B2G 1.4 and older, serialize binary data in JSON text strings (SLOW!) - print 'Bulk upload is not supported, uploading binary data with old slow format. Consider flashing your device to FFOS 2.0 or newer to enjoy faster upload speeds.' + print('Bulk upload is not supported, uploading binary data with old slow format. Consider flashing your device to FFOS 2.0 or newer to enjoy faster upload speeds.') uploadResponse = send_b2g_cmd(webappsActorName, 'uploadPackage') packageUploadActor = uploadResponse['actor'] chunk_size = 4*1024*1024 @@ -285,15 +286,15 @@ def delete_temp_file(): percentage_done = bytes_uploaded * 1.0 / file_size total_time = secs_elapsed / percentage_done time_left = total_time - secs_elapsed - print sizeof_fmt(bytes_uploaded) + " uploaded, {:5.1f} % done.".format(percentage_done*100.0) + ' Elapsed: ' + str(int(secs_elapsed)) + ' seconds. Time left: ' + str(datetime.timedelta(seconds=int(time_left))) + '. Data rate: {:5.2f} KB/second.'.format(bytes_uploaded / 1024.0 / secs_elapsed) + print(sizeof_fmt(bytes_uploaded) + " uploaded, {:5.1f} % done.".format(percentage_done*100.0) + ' Elapsed: ' + str(int(secs_elapsed)) + ' seconds. Time left: ' + str(datetime.timedelta(seconds=int(time_left))) + '. Data rate: {:5.2f} KB/second.'.format(bytes_uploaded / 1024.0 / secs_elapsed)) app_local_id = str(uuid.uuid4()) reply = send_b2g_cmd(webappsActorName, 'install', { 'appId': app_local_id, 'upload': packageUploadActor }) cur_time = time.time() secs_elapsed = cur_time - start_time - print 'Upload of ' + sizeof_fmt(file_size) + ' finished. Total time elapsed: ' + str(int(secs_elapsed)) + ' seconds. Data rate: {:5.2f} KB/second.'.format(file_size / 1024.0 / secs_elapsed) + print('Upload of ' + sizeof_fmt(file_size) + ' finished. Total time elapsed: ' + str(int(secs_elapsed)) + ' seconds. Data rate: {:5.2f} KB/second.'.format(file_size / 1024.0 / secs_elapsed)) if 'appId' not in reply: - print 'Error: Application install failed! ' + str(reply) + print('Error: Application install failed! ' + str(reply)) sys.exit() return reply['appId'] @@ -304,7 +305,7 @@ def b2g_app_command(app_command, app_name, print_errors_to_console = True): send_b2g_cmd(webappsActorName, app_command, { 'manifestURL': app['manifestURL'] }) return 0 if print_errors_to_console: - print 'Error! Application "' + app_name + '" was not found! Use the \'list\' command to find installed applications.' + print('Error! Application "' + app_name + '" was not found! Use the \'list\' command to find installed applications.') return 1 def b2g_memory(app_name): @@ -320,9 +321,9 @@ def b2g_memory(app_name): for k,v in measure.items(): if k != 'from': if k in ['otherSize', 'jsStringsSize', 'jsObjectsSize', 'styleSize', 'jsOtherSize', 'domSize', 'total']: # These are formatted in bytes - print k + ': ' + sizeof_fmt(v) + print(k + ': ' + sizeof_fmt(v)) else: - print k + ': ' + str(v) + print(k + ': ' + str(v)) def b2g_log(app_name, clear=False): global LOG_FORMAT @@ -337,7 +338,7 @@ def b2g_log(app_name, clear=False): if clear: send_b2g_cmd(consoleActor, 'clearMessagesCache') - print 'Cleared message log.' + print('Cleared message log.') return 0 msgs = send_b2g_cmd(consoleActor, 'startListeners', { 'listeners': ['PageError','ConsoleAPI','NetworkActivity','FileActivity'] }) @@ -397,7 +398,7 @@ def log_b2g_message(msg): channel = m['level'] + '/' text = set_color(channel + text, color) - print text + print(text) reset_color() msgs = send_b2g_cmd(consoleActor, 'getCachedMessages', { 'messageTypes': ['PageError', 'ConsoleAPI'] }) @@ -407,7 +408,7 @@ def log_b2g_message(msg): msg = read_b2g_response() log_b2g_message(msg) else: - print 'Application "' + sys.argv[2] + '" is not running!' + print('Application "' + sys.argv[2] + '" is not running!') def b2g_screenshot(filename): global deviceActorName @@ -424,7 +425,7 @@ def b2g_screenshot(filename): bytes_to_read = min(data_len - pos, chunk_size) data_reply = send_b2g_cmd(data_get_actor, 'substring', { 'start': str(pos), 'end': str(pos + bytes_to_read) }) if len(data_reply['substring']) != bytes_to_read: - print >> sys.stderr, 'Error! Expected to receive ' + str(bytes_to_read) + ' bytes of image data, but got ' + str(len(data_reply['substring'])) + ' bytes instead!' + print('Error! Expected to receive ' + str(bytes_to_read) + ' bytes of image data, but got ' + str(len(data_reply['substring'])) + ' bytes instead!', file=sys.stderr) sys.exit(1) data += data_reply['substring'] pos += bytes_to_read @@ -434,7 +435,7 @@ def b2g_screenshot(filename): delim = re.search(",", data).start() data_format = data[:delim] if data_format != "data:image/png;base64": - print >> sys.stderr, "Error: Received screenshot from device in an unexpected format '" + data_format + "'!" + print("Error: Received screenshot from device in an unexpected format '" + data_format + "'!", file=sys.stderr) sys.exit(1) data = data[delim+1:] @@ -453,25 +454,25 @@ def get_png_image_size(filename): width, height = get_png_image_size(filename) if width <= 0 or height <= 0: - print >> sys.stderr, "Wrote " + sizeof_fmt(len(binary_data)) + " to file '" + filename + "', but the contents may be corrupted!" + print("Wrote " + sizeof_fmt(len(binary_data)) + " to file '" + filename + "', but the contents may be corrupted!", file=sys.stderr) else: - print "Wrote " + sizeof_fmt(len(binary_data)) + " to file '" + filename + "' (" + str(width) + 'x' + str(height) + ' pixels).' + print("Wrote " + sizeof_fmt(len(binary_data)) + " to file '" + filename + "' (" + str(width) + 'x' + str(height) + ' pixels).') def b2g_get_description(desc): global deviceActorName data_reply = send_b2g_cmd(deviceActorName, 'getDescription') # First try an exact match to requested desc if desc and desc in data_reply['value']: - print desc + ': ' + str(data_reply['value'][desc]) + print(desc + ': ' + str(data_reply['value'][desc])) else: # Print all with case-insensitive substring search for k,v in data_reply['value'].items(): if not desc or desc.lower() in k.lower(): - print k + ': ' + str(v) + print(k + ': ' + str(v)) def main(): global b2g_socket, webappsActorName, deviceActorName, HOST, PORT, VERBOSE, ADB if len(sys.argv) < 2 or '--help' in sys.argv or 'help' in sys.argv or '-v' in sys.argv: - print '''Firefox OS Debug Bridge, a tool for automating FFOS device tasks from the command line. + print('''Firefox OS Debug Bridge, a tool for automating FFOS device tasks from the command line. Usage: ffdb.py , where command is one of: @@ -516,7 +517,7 @@ def main(): --simulator: Signal that we will be connecting to a FFOS simulator and not a real device. In the above, whenever a command requires an to be specified, either the human-readable name, - localId or manifestURL of the application can be used.''' + localId or manifestURL of the application can be used.''') sys.exit(0) @@ -528,7 +529,7 @@ def main(): for i in range(0, len(sys.argv)): if sys.argv[i] in options_with_value: if i+1 >= sys.argv or sys.argv[i+1].startswith('-'): - print >> sys.stderr, "Missing value for option " + sys.argv[i] +'!' + print("Missing value for option " + sys.argv[i] +'!', file=sys.stderr) sys.exit(1) if sys.argv[i] == '--host': HOST = sys.argv[i+1] @@ -549,11 +550,11 @@ def main(): if (HOST == 'localhost' or HOST == '127.0.0.1') and not connect_to_simulator: devices = adb_devices() if len(devices) == 0: - print 'Error! Failed to connect to B2G device debugger socket at address ' + HOST + ':' + str(PORT) + ' and no devices were detected via adb. Please double-check the following and try again: ' - print ' 1) The device is powered on and connected to the computer with an USB cable.' - print ' 2) ADB and DevTools debugging is enabled on the device. (Settings -> Developer -> Debugging via USB: "ADB and DevTools"' - print ' 3) The device is listed when you run "adb devices" on the command line.' - print ' 4) When launching ffdb, remember to acknowledge the "incoming debug connection" dialog if it pops up on the device.' + print('Error! Failed to connect to B2G device debugger socket at address ' + HOST + ':' + str(PORT) + ' and no devices were detected via adb. Please double-check the following and try again: ') + print(' 1) The device is powered on and connected to the computer with an USB cable.') + print(' 2) ADB and DevTools debugging is enabled on the device. (Settings -> Developer -> Debugging via USB: "ADB and DevTools"') + print(' 3) The device is listed when you run "adb devices" on the command line.') + print(' 4) When launching ffdb, remember to acknowledge the "incoming debug connection" dialog if it pops up on the device.') sys.exit(1) b2g_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if WINDOWS: @@ -565,18 +566,18 @@ def main(): if e[0] == 61 or e[0] == 107 or e[0] == 111: # 61 == Connection refused and 107+111 == Transport endpoint is not connected if (HOST == 'localhost' or HOST == '127.0.0.1') and not connect_to_simulator: cmd = [ADB, 'forward', 'tcp:'+str(PORT), 'localfilesystem:/data/local/debugger-socket'] - print 'Connection to ' + HOST + ':' + str(PORT) + ' refused, attempting to forward device debugger-socket to local address by calling ' + str(cmd) + ':' + print('Connection to ' + HOST + ':' + str(PORT) + ' refused, attempting to forward device debugger-socket to local address by calling ' + str(cmd) + ':') else: - print 'Error! Failed to connect to B2G ' + ('simulator' if connect_to_simulator else 'device') + ' debugger socket at address ' + HOST + ':' + str(PORT) + '!' + print('Error! Failed to connect to B2G ' + ('simulator' if connect_to_simulator else 'device') + ' debugger socket at address ' + HOST + ':' + str(PORT) + '!') sys.exit(1) try: retcode = subprocess.check_call(cmd) except Exception, e: - print 'Error! Failed to execute adb: ' + str(e) - print "Check that the device is connected properly, call 'adb devices' to list the detected devices." + print('Error! Failed to execute adb: ' + str(e)) + print("Check that the device is connected properly, call 'adb devices' to list the detected devices.") sys.exit(1) if retcode is not 0: - print 'Error! Failed to connect to B2G device and executing adb failed with return code ' + retcode + '!' + print('Error! Failed to connect to B2G device and executing adb failed with return code ' + retcode + '!') sys.exit(1) time.sleep(3) # Try again: @@ -584,7 +585,7 @@ def main(): b2g_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) b2g_socket.connect((HOST, PORT)) except Exception, e: - print 'Error! Failed to connect to B2G device debugger socket at address ' + HOST + ':' + str(PORT) + '!' + print('Error! Failed to connect to B2G device debugger socket at address ' + HOST + ':' + str(PORT) + '!') sys.exit(1) handshake = read_b2g_response() @@ -592,7 +593,7 @@ def main(): data = send_b2g_cmd('root', 'listTabs') if 'deviceActor' not in data: - print 'Error! Debugging connection was not available. Make sure that the "Remote debugging" developer option on the device is set to "ADB and Devtools".' + print('Error! Debugging connection was not available. Make sure that the "Remote debugging" developer option on the device is set to "ADB and Devtools".') sys.exit(1) deviceActorName = data['deviceActor'] logv('deviceActor: ' + deviceActorName) @@ -608,28 +609,28 @@ def main(): printed_apps = apps print_only_running = '--running' in sys.argv and not '--all' in sys.argv if print_only_running: # Print running apps only? - print 'Running applications by id:' + print('Running applications by id:') printed_apps = filter(lambda x: x['manifestURL'] in running_app_manifests, apps) else: - print 'Installed applications by id:' + print('Installed applications by id:') num_printed = print_applist(printed_apps, running_app_manifests, '--all' in sys.argv or print_only_running) if num_printed == 0: if print_only_running: - print ' No applications running.' + print(' No applications running.') else: - print ' No applications installed.' + print(' No applications installed.') if '--all' not in sys.argv and not print_only_running: - print 'Not showing built-in apps that cannot be uninstalled. Pass --all to include those in the listing.' + print('Not showing built-in apps that cannot be uninstalled. Pass --all to include those in the listing.') elif sys.argv[1] == 'launch' or sys.argv[1] == 'close' or sys.argv[1] == 'uninstall' or sys.argv[1] == 'getAppActor': if len(sys.argv) < 3: - print 'Error! No application name given! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ' + print('Error! No application name given! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ') return 1 ret = b2g_app_command(sys.argv[1], sys.argv[2]) if ret == 0 and '--log' in sys.argv: b2g_log(sys.argv[2]) elif sys.argv[1] == 'install': if len(sys.argv) < 3: - print 'Error! No application path given! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ' + print('Error! No application path given! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ') return 1 target_app_path = sys.argv[2] # Kill and uninstall old running app execution before starting. @@ -647,7 +648,7 @@ def main(): b2g_log(app_id) elif sys.argv[1] == 'navigate': if len(sys.argv) < 3: - print 'Error! No URL given! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ' + print('Error! No URL given! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ') return 1 browserActor = '' for app in apps: @@ -658,10 +659,10 @@ def main(): browserActor = browserActor['actor']['actor'] send_b2g_cmd(browserActor, 'navigateTo', { 'url': sys.argv[2]}) else: - print 'Web browser is not running!' + print('Web browser is not running!') elif sys.argv[1] == 'log': if len(sys.argv) < 3: - print 'Error! No application name given! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ' + print('Error! No application name given! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ') return 1 clear = '-c' in sys.argv or '-clear' in sys.argv or '--clear' in sys.argv b2g_log(sys.argv[2], clear) @@ -671,7 +672,7 @@ def main(): if len(sys.argv) >= 3: filename = sys.argv[2] if not filename.endswith('.png'): - print >> sys.stderr, "Writing screenshots only to .png files are supported!" + print("Writing screenshots only to .png files are supported!", file=sys.stderr) sys.exit(1) else: filename = time.strftime("screen_%Y%m%d_%H%M%S.png", time.gmtime()) @@ -681,18 +682,18 @@ def main(): b2g_get_pref(sys.argv[2] if len(sys.argv) >= 3 else None) elif sys.argv[1] == 'set': if len(sys.argv) < 3: - print 'Error! No pref name to set given! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ' + print('Error! No pref name to set given! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ') sys.exit(1) if len(sys.argv) < 4: - print 'Error! No value given to set! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ' + print('Error! No value given to set! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ') sys.exit(1) if len(sys.argv) > 4: - print 'Error! Too many arguments given (' + str(sys.argv) + '), need exactly four! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ' + print('Error! Too many arguments given (' + str(sys.argv) + '), need exactly four! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ') sys.exit(1) b2g_set_pref(sys.argv[2], sys.argv[3]) elif sys.argv[1] == 'unset': if len(sys.argv) < 3: - print 'Error! No pref name given! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ' + print('Error! No pref name given! Usage: ' + sys.argv[0] + ' ' + sys.argv[1] + ' ') sys.exit(1) b2g_set_pref(sys.argv[2], None) elif sys.argv[1] == 'hide-prompt': @@ -702,7 +703,7 @@ def main(): elif sys.argv[1] == 'desc': b2g_get_description(sys.argv[2] if len(sys.argv) >= 3 else None) else: - print "Unknown command '" + sys.argv[1] + "'! Pass --help for instructions." + print("Unknown command '" + sys.argv[1] + "'! Pass --help for instructions.") b2g_socket.close() return 0 @@ -713,5 +714,5 @@ def main(): logv('ffdb.py quitting with process exit code ' + str(returncode)) sys.exit(returncode) except KeyboardInterrupt: - print ('^C' if WINDOWS else '') + ' Aborted by user' + print(('^C' if WINDOWS else '') + ' Aborted by user') sys.exit(1) diff --git a/tools/file2json.py b/tools/file2json.py index 06770e7a9166..a411cf7927b7 100644 --- a/tools/file2json.py +++ b/tools/file2json.py @@ -10,6 +10,7 @@ VARNAME - the variable to store it in (the output will be VARNAME = [...]) ''' +from __future__ import print_function import os, sys data = open(sys.argv[1], 'rb').read() @@ -24,9 +25,9 @@ json = '[' + ''.join(lined) + ']' if len(sys.argv) < 3: - print json + print(json) else: - print 'var ' + sys.argv[2] + '=' + json + ';' + print('var ' + sys.argv[2] + '=' + json + ';') ''' or (but this fails, we get a string at runtime?) diff --git a/tools/file_packager.py b/tools/file_packager.py index 26e2ae92faab..a404a05a7b6f 100644 --- a/tools/file_packager.py +++ b/tools/file_packager.py @@ -60,6 +60,7 @@ to dds files in the browser, exactly the same as if this tool compressed them. ''' +from __future__ import print_function from toolchain_profiler import ToolchainProfiler if __name__ == '__main__': ToolchainProfiler.record_process_start() @@ -74,8 +75,8 @@ import json if len(sys.argv) == 1: - print '''Usage: file_packager.py TARGET [--preload A...] [--embed B...] [--exclude C...] [--no-closure] [--crunch[=X]] [--js-output=OUTPUT.js] [--no-force] [--use-preload-cache] [--no-heap-copy] [--separate-metadata] -See the source for more details.''' + print('''Usage: file_packager.py TARGET [--preload A...] [--embed B...] [--exclude C...] [--no-closure] [--crunch[=X]] [--js-output=OUTPUT.js] [--no-force] [--use-preload-cache] [--no-heap-copy] [--separate-metadata] +See the source for more details.''') sys.exit(0) DEBUG = os.environ.get('EMCC_DEBUG') @@ -154,7 +155,7 @@ try: from shared import CRUNCH except Exception, e: - print >> sys.stderr, 'could not import CRUNCH (make sure it is defined properly in ' + shared.hint_config_file_location() + ')' + print('could not import CRUNCH (make sure it is defined properly in ' + shared.hint_config_file_location() + ')', file=sys.stderr) raise e crunch = arg.split('=', 1)[1] if '=' in arg else '128' leading = '' @@ -175,11 +176,11 @@ if os.path.isfile(srcpath) or os.path.isdir(srcpath): data_files.append({ 'srcpath': srcpath, 'dstpath': dstpath, 'mode': mode, 'explicit_dst_path': uses_at_notation }) else: - print >> sys.stderr, 'Warning: ' + arg + ' does not exist, ignoring.' + print('Warning: ' + arg + ' does not exist, ignoring.', file=sys.stderr) elif leading == 'exclude': excluded_patterns.append(arg) else: - print >> sys.stderr, 'Unknown parameter:', arg + print('Unknown parameter:', arg, file=sys.stderr) sys.exit(1) if (not force) and len(data_files) == 0: @@ -254,7 +255,7 @@ def add(arg, dirname, names): fullname = os.path.join(dirname, name) if should_ignore(fullname): if DEBUG: - print >> sys.stderr, 'Skipping file "' + fullname + '" from inclusion in the emscripten virtual file system.' + print('Skipping file "' + fullname + '" from inclusion in the emscripten virtual file system.', file=sys.stderr) else: new_names.append(name) if not os.path.isdir(fullname): @@ -272,7 +273,7 @@ def add(arg, dirname, names): new_data_files.append(file_) data_files = filter(lambda file_: not os.path.isdir(file_['srcpath']), new_data_files) if len(data_files) == 0: - print >> sys.stderr, 'Nothing to do!' + print('Nothing to do!', file=sys.stderr) sys.exit(1) # Absolutize paths, and check that they make sense @@ -284,13 +285,13 @@ def add(arg, dirname, names): # we require that the destination not be under the current location path = file_['dstpath'] abspath = os.path.realpath(os.path.abspath(path)) # Use os.path.realpath to resolve any symbolic links to hard paths, to match the structure in curr_abspath. - if DEBUG: print >> sys.stderr, path, abspath, curr_abspath + if DEBUG: print(path, abspath, curr_abspath, file=sys.stderr) if not abspath.startswith(curr_abspath): - print >> sys.stderr, 'Error: Embedding "%s" which is below the current directory "%s". This is invalid since the current directory becomes the root that the generated code will see' % (path, curr_abspath) + print('Error: Embedding "%s" which is below the current directory "%s". This is invalid since the current directory becomes the root that the generated code will see' % (path, curr_abspath), file=sys.stderr) sys.exit(1) file_['dstpath'] = abspath[len(curr_abspath)+1:] if os.path.isabs(path): - print >> sys.stderr, 'Warning: Embedding an absolute file/directory name "' + path + '" to the virtual filesystem. The file will be made available in the relative path "' + file_['dstpath'] + '". You can use the explicit syntax --preload-file srcpath@dstpath to explicitly specify the target location the absolute source path should be directed to.' + print('Warning: Embedding an absolute file/directory name "' + path + '" to the virtual filesystem. The file will be made available in the relative path "' + file_['dstpath'] + '". You can use the explicit syntax --preload-file srcpath@dstpath to explicitly specify the target location the absolute source path should be directed to.', file=sys.stderr) for file_ in data_files: file_['dstpath'] = file_['dstpath'].replace(os.path.sep, '/') # name in the filesystem, native and emulated @@ -299,7 +300,7 @@ def add(arg, dirname, names): # make destination path always relative to the root file_['dstpath'] = posixpath.normpath(os.path.join('/', file_['dstpath'])) if DEBUG: - print >> sys.stderr, 'Packaging file "' + file_['srcpath'] + '" to VFS in path "' + file_['dstpath'] + '".' + print('Packaging file "' + file_['srcpath'] + '" to VFS in path "' + file_['dstpath'] + '".', file=sys.stderr) # Remove duplicates (can occur naively, for example preload dir/, preload dir/subdir/) seen = {} @@ -407,7 +408,7 @@ def was_seen(name): data.close() # TODO: sha256sum on data_target if start > 256*1024*1024: - print >> sys.stderr, 'warning: file packager is creating an asset bundle of %d MB. this is very large, and browsers might have trouble loading it. see https://hacks.mozilla.org/2015/02/synchronous-execution-and-filesystem-access-in-emscripten/' % (start/(1024*1024)) + print('warning: file packager is creating an asset bundle of %d MB. this is very large, and browsers might have trouble loading it. see https://hacks.mozilla.org/2015/02/synchronous-execution-and-filesystem-access-in-emscripten/' % (start/(1024*1024)), file=sys.stderr) create_preloaded = ''' Module['FS_createPreloadedFile'](this.name, null, byteArray, true, true, function() { @@ -854,7 +855,7 @@ def was_seen(name): if force or len(data_files) > 0: if jsoutput == None: - print ret + print(ret) else: # Overwrite the old jsoutput file (if exists) only when its content differs from the current generated one, otherwise leave the file untouched preserving its old timestamp if os.path.isfile(jsoutput): diff --git a/tools/find_bigis.py b/tools/find_bigis.py index 1261e7fff44e..07365a35c483 100644 --- a/tools/find_bigis.py +++ b/tools/find_bigis.py @@ -2,6 +2,7 @@ Simple tool to find big i types in an .ll file. Anything over i64 is of interest. ''' +from __future__ import print_function import os, sys, re filename = sys.argv[1] @@ -14,5 +15,5 @@ if size > 64: bigs.append(size) bigs.sort() -print bigs +print(bigs) diff --git a/tools/find_bigvars.py b/tools/find_bigvars.py index 6bee5dd44a4b..58b0c69b3dcf 100644 --- a/tools/find_bigvars.py +++ b/tools/find_bigvars.py @@ -2,6 +2,7 @@ Simple tool to find functions with lots of vars. ''' +from __future__ import print_function import os, sys, re filename = sys.argv[1] @@ -20,5 +21,5 @@ data.append([curr, size]) curr = None data.sort(lambda x, y: x[1] - y[1]) -print ''.join(['%6d : %s' % (x[1], x[0]) for x in data]) +print(''.join(['%6d : %s' % (x[1], x[0]) for x in data])) diff --git a/tools/js_optimizer.py b/tools/js_optimizer.py index d6b541bdf544..12ae5c8eb088 100644 --- a/tools/js_optimizer.py +++ b/tools/js_optimizer.py @@ -1,4 +1,5 @@ +from __future__ import print_function from toolchain_profiler import ToolchainProfiler if __name__ == '__main__': ToolchainProfiler.record_process_start() @@ -254,7 +255,7 @@ def minify_shell(self, shell, minify_whitespace, source_map=False): for key, value in self.globs.iteritems(): mapfile.write(value + ':' + key + '\n') mapfile.close() - print >> sys.stderr, 'wrote symbol map file to', self.symbols_file + print('wrote symbol map file to', self.symbols_file, file=sys.stderr) return code.replace('13371337', '0.0') @@ -279,9 +280,9 @@ def run_on_chunk(command): if os.environ.get('EMCC_SAVE_OPT_TEMP') and os.environ.get('EMCC_SAVE_OPT_TEMP') != '0': saved = 'save_' + os.path.basename(filename) while os.path.exists(saved): saved = 'input' + str(int(saved.replace('input', '').replace('.txt', ''))+1) + '.txt' - print >> sys.stderr, 'running js optimizer command', ' '.join(map(lambda c: c if c != filename else saved, command)) + print('running js optimizer command', ' '.join(map(lambda c: c if c != filename else saved, command)), file=sys.stderr) shutil.copyfile(filename, os.path.join(shared.get_emscripten_temp_dir(), saved)) - if shared.EM_BUILD_VERBOSE_LEVEL >= 3: print >> sys.stderr, 'run_on_chunk: ' + str(command) + if shared.EM_BUILD_VERBOSE_LEVEL >= 3: print('run_on_chunk: ' + str(command), file=sys.stderr) proc = subprocess.Popen(command, stdout=subprocess.PIPE) output = proc.communicate()[0] assert proc.returncode == 0, 'Error in optimizer (return code ' + str(proc.returncode) + '): ' + output @@ -292,7 +293,7 @@ def run_on_chunk(command): f = open(filename, 'wb') f.write(output) f.close() - if DEBUG and not shared.WINDOWS: print >> sys.stderr, '.' # Skip debug progress indicator on Windows, since it doesn't buffer well with multiple threads printing to console. + if DEBUG and not shared.WINDOWS: print('.', file=sys.stderr) # Skip debug progress indicator on Windows, since it doesn't buffer well with multiple threads printing to console. return filename except KeyboardInterrupt: # avoid throwing keyboard interrupts from a child process @@ -417,7 +418,7 @@ def check_symbol_mapping(p): chunks = map(lambda f: f[1], funcs) chunks = filter(lambda chunk: len(chunk) > 0, chunks) - if DEBUG and len(chunks) > 0: print >> sys.stderr, 'chunkification: num funcs:', len(funcs), 'actual num chunks:', len(chunks), 'chunk size range:', max(map(len, chunks)), '-', min(map(len, chunks)) + if DEBUG and len(chunks) > 0: print('chunkification: num funcs:', len(funcs), 'actual num chunks:', len(chunks), 'chunk size range:', max(map(len, chunks)), '-', min(map(len, chunks)), file=sys.stderr) funcs = None if len(chunks) > 0: @@ -454,13 +455,13 @@ def write_chunk(chunk, i): cores = min(cores, len(filenames)) if len(chunks) > 1 and cores >= 2: # We can parallelize - if DEBUG: print >> sys.stderr, 'splitting up js optimization into %d chunks, using %d cores (total: %.2f MB)' % (len(chunks), cores, total_size/(1024*1024.)) + if DEBUG: print('splitting up js optimization into %d chunks, using %d cores (total: %.2f MB)' % (len(chunks), cores, total_size/(1024*1024.)), file=sys.stderr) with ToolchainProfiler.profile_block('optimizer_pool'): pool = shared.Building.get_multiprocessing_pool() filenames = pool.map(run_on_chunk, commands, chunksize=1) else: # We can't parallize, but still break into chunks to avoid uglify/node memory issues - if len(chunks) > 1 and DEBUG: print >> sys.stderr, 'splitting up js optimization into %d chunks' % (len(chunks)) + if len(chunks) > 1 and DEBUG: print('splitting up js optimization into %d chunks' % (len(chunks)), file=sys.stderr) filenames = [run_on_chunk(command) for command in commands] else: filenames = [] @@ -484,17 +485,17 @@ def write_chunk(chunk, i): c.close() cld = cle if split_memory: - if DEBUG: print >> sys.stderr, 'running splitMemory on shell code' + if DEBUG: print('running splitMemory on shell code', file=sys.stderr) cld = run_on_chunk(js_engine + [JS_OPTIMIZER, cld, 'splitMemoryShell']) f = open(cld, 'a') f.write(suffix_marker) f.close() if closure: - if DEBUG: print >> sys.stderr, 'running closure on shell code' + if DEBUG: print('running closure on shell code', file=sys.stderr) cld = shared.Building.closure_compiler(cld, pretty='minifyWhitespace' not in passes) temp_files.note(cld) elif cleanup: - if DEBUG: print >> sys.stderr, 'running cleanup on shell code' + if DEBUG: print('running cleanup on shell code', file=sys.stderr) next = cld + '.cl.js' temp_files.note(next) proc = subprocess.Popen(js_engine + [JS_OPTIMIZER, cld, 'noPrintMetadata', 'JSDCE'] + (['minifyWhitespace'] if 'minifyWhitespace' in passes else []), stdout=open(next, 'w')) @@ -536,7 +537,7 @@ def sorter(x, y): if 'last' in passes and len(funcs) > 0: count = funcs[0][1].count('\n') if count > 3000: - print >> sys.stderr, 'warning: Output contains some very large functions (%s lines in %s), consider building source files with -Os or -Oz, and/or trying OUTLINING_LIMIT to break them up (see settings.js; note that the parameter there affects AST nodes, while we measure lines here, so the two may not match up)' % (count, funcs[0][0]) + print('warning: Output contains some very large functions (%s lines in %s), consider building source files with -Os or -Oz, and/or trying OUTLINING_LIMIT to break them up (see settings.js; note that the parameter there affects AST nodes, while we measure lines here, so the two may not match up)' % (count, funcs[0][0]), file=sys.stderr) for func in funcs: f.write(func[1]) diff --git a/tools/line_endings.py b/tools/line_endings.py index 7728beac047b..43b1a7c31e93 100644 --- a/tools/line_endings.py +++ b/tools/line_endings.py @@ -1,3 +1,4 @@ +from __future__ import print_function import sys, shutil, os def convert_line_endings(text, from_eol, to_eol): @@ -19,19 +20,19 @@ def check_line_endings(filename, expect_only_specific_line_endings=None, print_e try: data = open(filename, 'rb').read() except Exception, e: - if print_errors: print >> sys.stderr, "Unable to read file '" + filename + "'! " + str(e) + if print_errors: print("Unable to read file '" + filename + "'! " + str(e), file=sys.stderr) return 1 if len(data) == 0: - if print_errors: print >> sys.stderr, "Unable to read file '" + filename + "', or file was empty!" + if print_errors: print("Unable to read file '" + filename + "', or file was empty!", file=sys.stderr) return 1 bad_line_ending_index = data.find("\r\r\n") if bad_line_ending_index != -1: if print_errors: - print >> sys.stderr, "File '" + filename + "' contains BAD line endings of form \\r\\r\\n!" + print("File '" + filename + "' contains BAD line endings of form \\r\\r\\n!", file=sys.stderr) bad_line = data[max(0,bad_line_ending_index-50):min(len(data), bad_line_ending_index+50)] bad_line = bad_line.replace('\r', '\\r').replace('\n', '\\n') - print >> sys.stderr, "Content around the location: '" + bad_line + "'" + print("Content around the location: '" + bad_line + "'", file=sys.stderr) return 1 # Bad line endings in file, return a non-zero process exit code. has_dos_line_endings = False @@ -52,33 +53,33 @@ def check_line_endings(filename, expect_only_specific_line_endings=None, print_e if '\r' in data: old_osx_line_ending_example = data[max(0, data.find('\r') - 50):min(len(data), data.find('\r')+50)].replace('\r', '\\r').replace('\n', '\\n') if print_errors: - print >> sys.stderr, 'File \'' + filename + '\' contains OLD OSX line endings "\\r"' - print >> sys.stderr, "Content around an OLD OSX line ending location: '" + old_osx_line_ending_example + "'" + print('File \'' + filename + '\' contains OLD OSX line endings "\\r"', file=sys.stderr) + print("Content around an OLD OSX line ending location: '" + old_osx_line_ending_example + "'", file=sys.stderr) return 1 # Return a non-zero process exit code since we don't want to use the old OSX (9.x) line endings anywhere. if has_dos_line_endings and has_unix_line_endings: if print_errors: - print >> sys.stderr, 'File \'' + filename + '\' contains both DOS "\\r\\n" and UNIX "\\n" line endings! (' + str(dos_line_ending_count) + ' DOS line endings, ' + str(unix_line_ending_count) + ' UNIX line endings)' - print >> sys.stderr, "Content around a DOS line ending location: '" + dos_line_ending_example + "'" - print >> sys.stderr, "Content around an UNIX line ending location: '" + unix_line_ending_example + "'" + print('File \'' + filename + '\' contains both DOS "\\r\\n" and UNIX "\\n" line endings! (' + str(dos_line_ending_count) + ' DOS line endings, ' + str(unix_line_ending_count) + ' UNIX line endings)', file=sys.stderr) + print("Content around a DOS line ending location: '" + dos_line_ending_example + "'", file=sys.stderr) + print("Content around an UNIX line ending location: '" + unix_line_ending_example + "'", file=sys.stderr) return 1 # Mixed line endings elif print_info: - if has_dos_line_endings: print 'File \'' + filename + '\' contains DOS "\\r\\n" line endings.' - if has_unix_line_endings: print 'File \'' + filename +'\' contains UNIX "\\n" line endings.' + if has_dos_line_endings: print('File \'' + filename + '\' contains DOS "\\r\\n" line endings.') + if has_unix_line_endings: print('File \'' + filename +'\' contains UNIX "\\n" line endings.') if expect_only_specific_line_endings == '\n' and has_dos_line_endings: if print_errors: - print >> sys.stderr, 'File \'' + filename + '\' contains DOS "\\r\\n" line endings! (' + str(dos_line_ending_count) + ' DOS line endings), but expected only UNIX line endings!' - print >> sys.stderr, "Content around a DOS line ending location: '" + dos_line_ending_example + "'" + print('File \'' + filename + '\' contains DOS "\\r\\n" line endings! (' + str(dos_line_ending_count) + ' DOS line endings), but expected only UNIX line endings!', file=sys.stderr) + print("Content around a DOS line ending location: '" + dos_line_ending_example + "'", file=sys.stderr) return 1 # DOS line endings, but expected UNIX if expect_only_specific_line_endings == '\r\n' and has_unix_line_endings: if print_errors: - print >> sys.stderr, 'File \'' + filename + '\' contains UNIX "\\n" line endings! (' + str(unix_line_ending_count) + ' UNIX line endings), but expected only DOS line endings!' - print >> sys.stderr, "Content around a UNIX line ending location: '" + unix_line_ending_example + "'" + print('File \'' + filename + '\' contains UNIX "\\n" line endings! (' + str(unix_line_ending_count) + ' UNIX line endings), but expected only DOS line endings!', file=sys.stderr) + print("Content around a UNIX line ending location: '" + unix_line_ending_example + "'", file=sys.stderr) return 1 # UNIX line endings, but expected DOS else: return 0 if __name__ == '__main__': if len(sys.argv) != 2: - print >> sys.stderr, 'Unknown command line ' + str(sys.argv) + '!' - print >> sys.stderr, 'Usage: ' + sys.argv[0] + ' ' + print('Unknown command line ' + str(sys.argv) + '!', file=sys.stderr) + print('Usage: ' + sys.argv[0] + ' ', file=sys.stderr) sys.exit(1) sys.exit(check_line_endings(sys.argv[1], print_info=True)) diff --git a/tools/ll-strip.py b/tools/ll-strip.py index a08da47885d9..3ef6695b52e3 100755 --- a/tools/ll-strip.py +++ b/tools/ll-strip.py @@ -1,10 +1,11 @@ #!/usr/bin/python2 +from __future__ import print_function import sys, re def print_usage(): - print >> sys.stderr, "Usage: ll-strip.py file from to" - print >> sys.stderr, "\tStrip function bodies in all ll file in the [from, to] range" + print("Usage: ll-strip.py file from to", file=sys.stderr) + print("\tStrip function bodies in all ll file in the [from, to] range", file=sys.stderr) sys.exit(1) try: @@ -28,7 +29,7 @@ def print_usage(): line = orig_line.strip() if func_start.match(line): if in_function: - print >> sys.stderr, "Discovered a function inside another function!" + print("Discovered a function inside another function!", file=sys.stderr) sys.exit(1) in_function = True line_number = 0 @@ -36,7 +37,7 @@ def print_usage(): function_counter = function_counter + 1 elif func_end.match(line): if not in_function: - print >> sys.stderr, "Discovered a function end without a matching beginning!" + print("Discovered a function end without a matching beginning!", file=sys.stderr) sys.exit(1) in_function = False line_number = 0 @@ -50,7 +51,7 @@ def print_usage(): #import pdb;pdb.set_trace() if line != dummy_stmt: skip = True - print dummy_stmt + print(dummy_stmt) if not skip: - print orig_line.rstrip("\n") + print(orig_line.rstrip("\n")) diff --git a/tools/make_file.py b/tools/make_file.py index 720eb0e494dc..f9de32a79e85 100644 --- a/tools/make_file.py +++ b/tools/make_file.py @@ -4,6 +4,7 @@ that and make a proper file out of it ''' +from __future__ import print_function import os, sys, re data = open(sys.argv[1], 'r').read() @@ -12,8 +13,8 @@ data = [x&0xff for x in data] string = ''.join([chr(item) for item in data]) out = open(sys.argv[1]+'.' + (sys.argv[2] if len(sys.argv) >= 3 else 'raw'), 'wb') -print data[0:80] -print string[0:80] +print(data[0:80]) +print(string[0:80]) out.write(string) out.close() diff --git a/tools/make_minigzip.py b/tools/make_minigzip.py index 4e4b14e29917..85b6db179956 100644 --- a/tools/make_minigzip.py +++ b/tools/make_minigzip.py @@ -1,14 +1,15 @@ +from __future__ import print_function import os, sys from subprocess import Popen, PIPE, STDOUT import shared -print 'Building zlib' +print('Building zlib') emscripten_temp_dir = shared.get_emscripten_temp_dir() zlib = shared.Building.build_library('zlib', emscripten_temp_dir, emscripten_temp_dir, ['libz.a'], make_args=['libz.a'], copy_project=True, source_dir=shared.path_from_root('tests', 'zlib'))[0] -print 'Building minigzip' +print('Building minigzip') Popen([shared.PYTHON, shared.EMCC, '-O2', shared.path_from_root('tests', 'zlib', 'minigzip.c'), zlib, '-o', shared.path_from_root('tools', 'minigzip.js')]).communicate() diff --git a/tools/merge_asm.py b/tools/merge_asm.py index fe143a89f852..f928d1dc0148 100755 --- a/tools/merge_asm.py +++ b/tools/merge_asm.py @@ -6,18 +6,19 @@ that would be harmful to asm.js code. ''' +from __future__ import print_function import sys import shared try: me, in_shell, in_asm, outfile = sys.argv[:4] except: - print >> sys.stderr, 'usage: emlink.py [input file] [shell output file] [asm output file]' + print('usage: emlink.py [input file] [shell output file] [asm output file]', file=sys.stderr) sys.exit(1) -print 'Shell input:', in_shell -print 'Asm input:', in_asm -print 'Input file:', outfile +print('Shell input:', in_shell) +print('Asm input:', in_asm) +print('Input file:', outfile) shared.try_delete(outfile) diff --git a/tools/merge_pair.py b/tools/merge_pair.py index 4c2311098c6e..8580eb7ab204 100644 --- a/tools/merge_pair.py +++ b/tools/merge_pair.py @@ -7,6 +7,7 @@ where a change occurs shows which function is the culprit. ''' +from __future__ import print_function import os, sys, shutil import asm_module, shared, shutil @@ -22,7 +23,7 @@ out = sys.argv[4] funcs = list(left_asm.funcs) -print 'total funcs:', len(funcs) +print('total funcs:', len(funcs)) left_map = left_asm.get_funcs_map() right_map = right_asm.get_funcs_map() @@ -32,7 +33,7 @@ f = funcs[i] if f in right_map: # TODO: fix left_map[f] = right_map[f] -print 'merging in the first %d from the second file' % n +print('merging in the first %d from the second file' % n) left_asm.apply_funcs_map(left_map) diff --git a/tools/namespacer.py b/tools/namespacer.py index 81b8d2d16ec3..9b29d5cd7abf 100644 --- a/tools/namespacer.py +++ b/tools/namespacer.py @@ -25,6 +25,7 @@ a more OO boilerplate on top of that. ''' +from __future__ import print_function import os, sys, json js = open(sys.argv[1], 'r').read() @@ -91,5 +92,5 @@ def finalize(line): except: return line -print 'var ModuleNames = ' + '\n'.join(map(finalize, json.dumps(space, sort_keys=True, indent=2).split('\n'))) +print('var ModuleNames = ' + '\n'.join(map(finalize, json.dumps(space, sort_keys=True, indent=2).split('\n')))) diff --git a/tools/nativize_llvm.py b/tools/nativize_llvm.py index e80264adcc86..36962487882e 100755 --- a/tools/nativize_llvm.py +++ b/tools/nativize_llvm.py @@ -9,6 +9,7 @@ * Use g++ to link it to an executable ''' +from __future__ import print_function import os, sys from subprocess import Popen, PIPE, STDOUT @@ -21,22 +22,22 @@ def path_from_root(*pathelems): filename = sys.argv[1] libs = sys.argv[2:] # e.g.: dl for dlopen/dlclose, util for openpty/forkpty -print 'bc => clean bc' +print('bc => clean bc') Popen([LLVM_OPT, filename, '-strip-debug', '-o', filename + '.clean.bc']).communicate()[0] -print 'bc => s' +print('bc => s') for params in [['-march=x86'], ['-march=x86-64']]: # try x86, then x86-64 FIXME - print 'params', params + print('params', params) for triple in [['-mtriple=i386-pc-linux-gnu'], []]: Popen([LLVM_COMPILER] + params + triple + [filename + '.clean.bc', '-o', filename + '.s']).communicate()[0] - print 's => o' + print('s => o') Popen(['as', filename + '.s', '-o', filename + '.o']).communicate()[0] if os.path.exists(filename + '.o'): break if os.path.exists(filename + '.o'): break if not os.path.exists(filename + '.o'): - print >> sys.stderr, 'tools/nativize_llvm.py: Failed to convert "' + filename + '" to "' + filename + '.o"!' + print('tools/nativize_llvm.py: Failed to convert "' + filename + '" to "' + filename + '.o"!', file=sys.stderr) sys.exit(1) -print 'o => runnable' +print('o => runnable') Popen(['g++', path_from_root('system', 'lib', 'debugging.cpp'), filename + '.o', '-o', filename + '.run'] + ['-l' + lib for lib in libs]).communicate()[0] diff --git a/tools/parse_unaligned.py b/tools/parse_unaligned.py index 614ea69268e9..0243e440d6d3 100644 --- a/tools/parse_unaligned.py +++ b/tools/parse_unaligned.py @@ -1,3 +1,4 @@ +from __future__ import print_function import os, sys from subprocess import Popen, PIPE, STDOUT @@ -10,7 +11,7 @@ output = Popen(['c++filt', x], stdout=PIPE).communicate()[0] if output not in shown: shown.add(output) - print output, + print(output, end=' ') except: pass diff --git a/tools/profile_stripper.py b/tools/profile_stripper.py index 3e538ef38cff..aca2c9d62a95 100644 --- a/tools/profile_stripper.py +++ b/tools/profile_stripper.py @@ -2,6 +2,7 @@ # # profile file, js file +from __future__ import print_function import sys, json used = json.loads(open(sys.argv[1]).read()) @@ -30,10 +31,10 @@ end = line.index(']') contents = line[start:end] fixed = map(lambda name: '"' + name + '"' if not used.get(name) else name, contents.split(',')) - print (line[:start] + ','.join(fixed) + line[end:]).replace('""', '') + print((line[:start] + ','.join(fixed) + line[end:]).replace('""', '')) else: if show: - print orig, + print(orig, end=' ') if orig.startswith('}'): show = True diff --git a/tools/profile_used.py b/tools/profile_used.py index 45420e0f0a72..1a395f477e8d 100644 --- a/tools/profile_used.py +++ b/tools/profile_used.py @@ -4,14 +4,15 @@ ''' # then strip with profile_strip.py +from __future__ import print_function import sys -print 'var usedFunctions = {};' +print('var usedFunctions = {};') for line in open(sys.argv[1]).readlines(): line = line.strip() - print line + print(line) if line.startswith('function _') and line.endswith(('){', ') {')): name = line.split(' ')[1].split('(')[0] - print 'usedFunctions["%s"] = 1;' % name + print('usedFunctions["%s"] = 1;' % name) diff --git a/tools/reproduceriter.py b/tools/reproduceriter.py index c820978bf4c8..79964e766f14 100755 --- a/tools/reproduceriter.py +++ b/tools/reproduceriter.py @@ -104,6 +104,7 @@ ''' +from __future__ import print_function import os, sys, shutil, re assert len(sys.argv) >= 4, 'Usage: reproduceriter.py IN_DIR OUT_DIR FIRST_JS [WINDOW_LOCATION]' @@ -126,19 +127,19 @@ # Copy project -print 'copying tree...' +print('copying tree...') shutil.copytree(in_dir, out_dir) # Add customizations in all JS files -print 'add customizations...' +print('add customizations...') for parent, dirs, files in os.walk(out_dir): for filename in files: if filename.endswith('.js'): fullname = os.path.join(parent, filename) - print ' ', fullname + print(' ', fullname) js = open(fullname).read() js = re.sub('document\.on(\w+) ?= ?([\w.$]+)', lambda m: 'Recorder.onEvent("' + m.group(1) + '", ' + m.group(2) + ')', js) js = re.sub('''([\w.'"\[\]]+)\.addEventListener\(([\w,. $]+)\)''', lambda m: 'Recorder.addListener(' + m.group(1) + ', ' + m.group(2) + ')', js) @@ -146,7 +147,7 @@ # Add our boilerplate -print 'add boilerplate...' +print('add boilerplate...') open(os.path.join(out_dir, first_js), 'w').write( (open(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'src', 'headless.js')).read() % ( @@ -156,5 +157,5 @@ open(os.path.join(in_dir, first_js)).read() + ('\nwindow.runEventLoop();\n' if shell else '') ) -print 'done!' +print('done!') diff --git a/tools/scan_js.py b/tools/scan_js.py index eeff7c7cb88f..c1c19d9dd9d7 100644 --- a/tools/scan_js.py +++ b/tools/scan_js.py @@ -2,6 +2,7 @@ Finds why a .js file is large by printing functions by size ''' +from __future__ import print_function import os, sys funcs = [] @@ -16,5 +17,5 @@ funcs.append((inside, i-start)) inside = None -print '\n'.join(map(lambda func: str(func[1]) + ':' + func[0], sorted(funcs, key=lambda func: -func[1]))) +print('\n'.join(map(lambda func: str(func[1]) + ':' + func[0], sorted(funcs, key=lambda func: -func[1])))) diff --git a/tools/scan_ll.py b/tools/scan_ll.py index d7d420577970..0ce62803cfc5 100644 --- a/tools/scan_ll.py +++ b/tools/scan_ll.py @@ -2,6 +2,7 @@ Finds why an .ll file is large by printing functions by size ''' +from __future__ import print_function import os, sys funcs = [] @@ -14,5 +15,5 @@ elif line.startswith('}'): funcs.append((inside, i-start)) -print '\n'.join(map(lambda func: str(func[1]) + ':' + func[0], sorted(funcs, key=lambda func: -func[1]))) +print('\n'.join(map(lambda func: str(func[1]) + ':' + func[0], sorted(funcs, key=lambda func: -func[1])))) diff --git a/tools/scons/site_scons/site_tools/emscripten/emscripten.py b/tools/scons/site_scons/site_tools/emscripten/emscripten.py index 7ab6aeb99aa8..fb2c95ccd51f 100644 --- a/tools/scons/site_scons/site_tools/emscripten/emscripten.py +++ b/tools/scons/site_scons/site_tools/emscripten/emscripten.py @@ -1,5 +1,6 @@ #!/usr/bin/env python2 +from __future__ import print_function import os def generate(env, emscripten_path=None, **kw): @@ -17,7 +18,7 @@ def generate(env, emscripten_path=None, **kw): try: exec(open(CONFIG_FILE, 'r').read()) except Exception, e: - print >> sys.stderr, 'Error in evaluating %s (at %s): %s' % (EM_CONFIG, CONFIG_FILE, str(e)) + print('Error in evaluating %s (at %s): %s' % (EM_CONFIG, CONFIG_FILE, str(e)), file=sys.stderr) sys.exit(1) emscripten_path = EMSCRIPTEN_ROOT diff --git a/tools/shared.py b/tools/shared.py index 6eec3ee64010..c9de1c6ba98a 100644 --- a/tools/shared.py +++ b/tools/shared.py @@ -1,3 +1,4 @@ +from __future__ import print_function from toolchain_profiler import ToolchainProfiler import shutil, time, os, sys, json, tempfile, copy, shlex, atexit, subprocess, hashlib, cPickle, re, errno from subprocess import Popen, PIPE, STDOUT @@ -55,9 +56,9 @@ def communicate(self, input=None): # If caller never wanted to PIPE stdout or stderr, route the output back to screen to avoid swallowing output. if self.stdout == None and self.stdout_ == PIPE and len(output[0].strip()) > 0: - print >> sys.stdout, output[0] + print(output[0], file=sys.stdout) if self.stderr == None and self.stderr_ == PIPE and len(output[1].strip()) > 0: - print >> sys.stderr, output[1] + print(output[1], file=sys.stderr) # Return a mock object to the caller. This works as long as all emscripten code immediately .communicate()s the result, and doesn't # leave the process object around for longer/more exotic uses. @@ -237,7 +238,7 @@ def new(*args): # write open(CONFIG_FILE, 'w').write(config_file) - print >> sys.stderr, ''' + print(''' ============================================================================== Welcome to Emscripten! @@ -255,7 +256,7 @@ def new(*args): This command will now exit. When you are done editing those paths, re-run it. ============================================================================== -''' % (EM_CONFIG, CONFIG_FILE, llvm_root, node, __rootpath__) +''' % (EM_CONFIG, CONFIG_FILE, llvm_root, node, __rootpath__), file=sys.stderr) sys.exit(0) try: @@ -385,17 +386,17 @@ def check_fastcomp(): if not Settings.WASM_BACKEND: if not has_asm_js_target(targets): logging.critical('fastcomp in use, but LLVM has not been built with the JavaScript backend as a target, llc reports:') - print >> sys.stderr, '===========================================================================' - print >> sys.stderr, targets - print >> sys.stderr, '===========================================================================' + print('===========================================================================', file=sys.stderr) + print(targets, file=sys.stderr) + print('===========================================================================', file=sys.stderr) logging.critical('you can fall back to the older (pre-fastcomp) compiler core, although that is not recommended, see http://kripken.github.io/emscripten-site/docs/building_from_source/LLVM-Backend.html') return False else: if not has_wasm_target(targets): logging.critical('WebAssembly set as target, but LLVM has not been built with the WebAssembly backend, llc reports:') - print >> sys.stderr, '===========================================================================' - print >> sys.stderr, targets - print >> sys.stderr, '===========================================================================' + print('===========================================================================', file=sys.stderr) + print(targets, file=sys.stderr) + print('===========================================================================', file=sys.stderr) return False if not Settings.WASM_BACKEND: @@ -582,7 +583,7 @@ def check_sanity(force=False): except Exception, e: # Any error here is not worth failing on - print 'WARNING: sanity check failed to run', e + print('WARNING: sanity check failed to run', e) finally: ToolchainProfiler.exit_block('sanity') @@ -883,7 +884,7 @@ def set_logging(): try: JS_ENGINES = [JS_ENGINE] except Exception, e: - print 'ERROR: %s does not seem to have JS_ENGINES or JS_ENGINE set up' % EM_CONFIG + print('ERROR: %s does not seem to have JS_ENGINES or JS_ENGINE set up' % EM_CONFIG) raise try: @@ -1150,7 +1151,7 @@ def load(self, args=[]): # Load the JS defaults into python settings = open(path_from_root('src', 'settings.js')).read().replace('//', '#') settings = re.sub(r'var ([\w\d]+)', r'self.attrs["\1"]', settings) - exec settings + exec(settings) # Apply additional settings. First -O, then -s for i in range(len(args)): @@ -1165,7 +1166,7 @@ def load(self, args=[]): for i in range(len(args)): if args[i] == '-s': declare = re.sub(r'([\w\d]+)\s*=\s*(.+)', r'self.attrs["\1"]=\2;', args[i+1]) - exec declare + exec(declare) if get_llvm_target() == WASM_TARGET: self.attrs['WASM_BACKEND'] = 1 @@ -1279,7 +1280,7 @@ def extract_archive_contents(f): 'files': contents } except Exception, e: - print >> sys.stderr, 'extract archive contents('+str(f)+') failed with error: ' + str(e) + print('extract archive contents('+str(f)+') failed with error: ' + str(e), file=sys.stderr) finally: os.chdir(cwd) @@ -1529,7 +1530,7 @@ def configure(args, stdout=None, stderr=None, env=None): # do builds natively with Clang. This is a heuristic emulation that may or may not work. env['EMMAKEN_JUST_CONFIGURE'] = '1' try: - if EM_BUILD_VERBOSE_LEVEL >= 3: print >> sys.stderr, 'configure: ' + str(args) + if EM_BUILD_VERBOSE_LEVEL >= 3: print('configure: ' + str(args), file=sys.stderr) process = Popen(args, stdout=None if EM_BUILD_VERBOSE_LEVEL >= 2 else stdout, stderr=None if EM_BUILD_VERBOSE_LEVEL >= 1 else stderr, env=env) process.communicate() except Exception, e: @@ -1561,7 +1562,7 @@ def make(args, stdout=None, stderr=None, env=None): try: # On Windows, run the execution through shell to get PATH expansion and executable extension lookup, e.g. 'sdl2-config' will match with 'sdl2-config.bat' in PATH. - if EM_BUILD_VERBOSE_LEVEL >= 3: print >> sys.stderr, 'make: ' + str(args) + if EM_BUILD_VERBOSE_LEVEL >= 3: print('make: ' + str(args), file=sys.stderr) process = Popen(args, stdout=None if EM_BUILD_VERBOSE_LEVEL >= 2 else stdout, stderr=None if EM_BUILD_VERBOSE_LEVEL >= 1 else stderr, env=env, shell=WINDOWS) process.communicate() except Exception, e: diff --git a/tools/stubify_ll.py b/tools/stubify_ll.py index 1e10ae4e180c..fcfc23524c92 100644 --- a/tools/stubify_ll.py +++ b/tools/stubify_ll.py @@ -2,6 +2,7 @@ # given a file of ll and a list of names to retain, makes all other functions into stubs. # you can then build with -s LINKABLE=1 and see any compilation errors on the specific functions +from __future__ import print_function import os, sys kill = False @@ -19,10 +20,10 @@ kill = True else: line = line.replace(' internal ', ' ') - print line + print(line) else: if not kill: - print line + print(line) else: if line == '}': kill = False diff --git a/tools/system_libs.py b/tools/system_libs.py index 99bbbbdbdc80..fb7a62193649 100755 --- a/tools/system_libs.py +++ b/tools/system_libs.py @@ -1,3 +1,4 @@ +from __future__ import print_function import os, json, logging, zipfile, glob, shutil import shared from subprocess import Popen, CalledProcessError @@ -727,6 +728,6 @@ def process_args(args, settings): return args def show_ports(): - print 'Available ports:' + print('Available ports:') for port in ports.ports: - print ' ', port.show() + print(' ', port.show()) diff --git a/tools/tempfiles.py b/tools/tempfiles.py index f3fdb48c0489..d7ff26fff942 100644 --- a/tools/tempfiles.py +++ b/tools/tempfiles.py @@ -1,3 +1,4 @@ +from __future__ import print_function import os import shutil import tempfile @@ -67,7 +68,7 @@ def get_dir(self): def clean(self): if self.save_debug_files: import sys - print >> sys.stderr, 'not cleaning up temp files since in debug-save mode, see them in %s' % (self.tmp,) + print('not cleaning up temp files since in debug-save mode, see them in %s' % (self.tmp,), file=sys.stderr) return for filename in self.to_clean: try_delete(filename) diff --git a/tools/traverse.py b/tools/traverse.py index 05f14597a226..a891fd2e3416 100755 --- a/tools/traverse.py +++ b/tools/traverse.py @@ -4,6 +4,7 @@ simple tool to run emcc and clang on C testcases each in a separate subdir of the current dir ''' +from __future__ import print_function import os, sys __rootpath__ = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -16,7 +17,7 @@ def path_from_root(*pathelems): curr = os.getcwd() for d in os.listdir(curr): - print '(' + d + ') ', + print('(' + d + ') ', end=' ') os.chdir(curr) if os.path.isdir(d): os.chdir(d) @@ -35,16 +36,16 @@ def path_from_root(*pathelems): n3 = execute(['./a.out'], stdout=PIPE)[0] if js == n1: - print 'ok' + print('ok') elif js == n2: - print 'emcc and clang -O2 both equally wrong' + print('emcc and clang -O2 both equally wrong') elif js == n3: - print 'emcc agrees with gcc, so probably ok' + print('emcc agrees with gcc, so probably ok') else: - print - print 'js ', js, - print 'c0 ', n1, - print 'c2 ', n2, - print 'g ', n3, - print 'fail!!!', d + print() + print('js ', js, end=' ') + print('c0 ', n1, end=' ') + print('c2 ', n2, end=' ') + print('g ', n3, end=' ') + print('fail!!!', d) diff --git a/tools/validate_asmjs.py b/tools/validate_asmjs.py index 8adef753ba49..f46bb96dd17d 100755 --- a/tools/validate_asmjs.py +++ b/tools/validate_asmjs.py @@ -11,6 +11,7 @@ # This script depends on the SpiderMonkey JS engine, which must be present in PATH in order for this script to function. +from __future__ import print_function import subprocess, sys, re, tempfile, os, time import shared @@ -18,22 +19,22 @@ def validate_asmjs_jsfile(filename, muteOutput): cmd = shared.SPIDERMONKEY_ENGINE + ['-c', filename] if not shared.SPIDERMONKEY_ENGINE or cmd[0] == 'js-not-found' or len(cmd[0].strip()) == 0: - print >> sys.stderr, 'Could not find SpiderMonkey engine! Please set its location to SPIDERMONKEY_ENGINE in your ' + shared.hint_config_file_location() + ' configuration file!' + print('Could not find SpiderMonkey engine! Please set its location to SPIDERMONKEY_ENGINE in your ' + shared.hint_config_file_location() + ' configuration file!', file=sys.stderr) return False try: process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) except Exception, e: - print >> sys.stderr, 'Executing command ' + str(cmd) + ' failed due to an exception: ' + str(e) + '!' + print('Executing command ' + str(cmd) + ' failed due to an exception: ' + str(e) + '!', file=sys.stderr) return False (stdout, stderr) = process.communicate() if not muteOutput: if len(stdout.strip()) > 0: - print stdout.strip() + print(stdout.strip()) if len(stderr.strip()) > 0: # Pretty-print the output not to contain a spurious warning. warning_re = re.compile(re.escape('warning: successfully compiled asm.js'), re.IGNORECASE) stderr = warning_re.sub(' successfully compiled asm.js', stderr) - print >> sys.stderr, stderr.strip() + print(stderr.strip(), file=sys.stderr) if 'successfully compiled asm.js' in stderr.lower(): return True else: @@ -64,7 +65,7 @@ def validate_asmjs(filename, muteOutput): if os.path.isfile(js_file): return validate_asmjs(js_file, muteOutput) if not muteOutput: - print >> sys.stderr, 'Error: the file does not contain any "use asm" modules.' + print('Error: the file does not contain any "use asm" modules.', file=sys.stderr) return False else: return True @@ -73,13 +74,13 @@ def validate_asmjs(filename, muteOutput): def main(): if len(sys.argv) < 2: - print 'Usage: validate_asmjs ' + print('Usage: validate_asmjs ') return 2 if validate_asmjs(sys.argv[1], muteOutput=False): - print "OK: File '" + sys.argv[1] + "' validates as asm.js" + print("OK: File '" + sys.argv[1] + "' validates as asm.js") return 0 else: - print "FAIL: File '" + sys.argv[1] + "' is not valid asm.js" + print("FAIL: File '" + sys.argv[1] + "' is not valid asm.js") return 1 if __name__ == '__main__': diff --git a/tools/webidl_binder.py b/tools/webidl_binder.py index 87724641c130..05383961bea7 100644 --- a/tools/webidl_binder.py +++ b/tools/webidl_binder.py @@ -5,6 +5,7 @@ http://kripken.github.io/emscripten-site/docs/porting/connecting_cpp_and_javascript/WebIDL-Binder.html ''' +from __future__ import print_function import os, sys import shared @@ -23,7 +24,7 @@ # DEBUG=1 will print debug info in render_function DEBUG = os.environ.get('IDL_VERBOSE') is '1' -if DEBUG: print "Debug print ON, CHECKS=%s" % CHECKS +if DEBUG: print("Debug print ON, CHECKS=%s" % CHECKS) class Dummy(object): def __init__(self, init): @@ -340,13 +341,13 @@ def render_function(class_name, func_name, sigs, return_type, non_pointer, copy, all_args = sigs.get(max_args) if DEBUG: - print 'renderfunc', class_name, func_name, sigs.keys(), return_type, constructor + print('renderfunc', class_name, func_name, sigs.keys(), return_type, constructor) for i in range(max_args): a = all_args[i] if isinstance(a, WebIDL.IDLArgument): - print (" arg%d" % i), a.identifier, a.type, a.optional + print((" arg%d" % i), a.identifier, a.type, a.optional) else: - print " arg%d" % i + print(" arg%d" % i) # JS