//build: Convert print statements to Python 3 style
Ran "2to3 -w -n -f print ./base" and manually added imports.
There are no intended behaviour changes.
Bug: 941669
Change-Id: Ie2830e213eae3a5d7753ce503020e02811b726d1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1585890
Commit-Queue: Raul Tambre <[email protected]>
Reviewed-by: Nico Weber <[email protected]>
Reviewed-by: Dirk Pranke <[email protected]>
Auto-Submit: Raul Tambre <[email protected]>
Cr-Commit-Position: refs/heads/master@{#658917}
diff --git a/build/android/adb_command_line.py b/build/android/adb_command_line.py
index 5763da4..9829974 100755
--- a/build/android/adb_command_line.py
+++ b/build/android/adb_command_line.py
@@ -5,6 +5,8 @@
"""Utility for reading / writing command-line flag files on device(s)."""
+from __future__ import print_function
+
import argparse
import logging
import sys
@@ -80,14 +82,14 @@
updated_values = all_devices.pMap(update_flags).pGet(None)
- print '%sCurrent flags (in %s):' % (action, args.name)
+ print('%sCurrent flags (in %s):' % (action, args.name))
for d, desc, flags in updated_values:
if flags:
# Shell-quote flags for easy copy/paste as new args on the terminal.
quoted_flags = ' '.join(cmd_helper.SingleQuote(f) for f in sorted(flags))
else:
quoted_flags = '( empty )'
- print ' %s (%s): %s' % (d, desc, quoted_flags)
+ print(' %s (%s): %s' % (d, desc, quoted_flags))
return 0
diff --git a/build/android/adb_logcat_monitor.py b/build/android/adb_logcat_monitor.py
index d3cc67d..a919722 100755
--- a/build/android/adb_logcat_monitor.py
+++ b/build/android/adb_logcat_monitor.py
@@ -16,6 +16,8 @@
early enough to not miss anything.
"""
+from __future__ import print_function
+
import logging
import os
import re
@@ -98,7 +100,7 @@
"""Monitor adb forever. Expects a SIGINT (Ctrl-C) to kill."""
# We create the directory to ensure 'run once' semantics
if os.path.exists(base_dir):
- print 'adb_logcat_monitor: %s already exists? Cleaning' % base_dir
+ print('adb_logcat_monitor: %s already exists? Cleaning' % base_dir)
shutil.rmtree(base_dir, ignore_errors=True)
os.makedirs(base_dir)
@@ -150,7 +152,7 @@
if __name__ == '__main__':
if 2 <= len(sys.argv) <= 3:
- print 'adb_logcat_monitor: Initializing'
+ print('adb_logcat_monitor: Initializing')
sys.exit(main(*sys.argv[1:3]))
- print 'Usage: %s <base_dir> [<adb_binary_path>]' % sys.argv[0]
+ print('Usage: %s <base_dir> [<adb_binary_path>]' % sys.argv[0])
diff --git a/build/android/apk_operations.py b/build/android/apk_operations.py
index 23001b7d..1d657611 100755
--- a/build/android/apk_operations.py
+++ b/build/android/apk_operations.py
@@ -6,6 +6,8 @@
# Using colorama.Fore/Back/Style members
# pylint: disable=no-member
+from __future__ import print_function
+
import argparse
import collections
import json
@@ -222,7 +224,7 @@
if ShouldWarnFakeFeatureModuleInstallFlag(device):
msg = ('Command line has no %s: Fake modules will be ignored.' %
FAKE_FEATURE_MODULE_INSTALL)
- print _Colorize(msg, colorama.Fore.YELLOW + colorama.Style.BRIGHT)
+ print(_Colorize(msg, colorama.Fore.YELLOW + colorama.Style.BRIGHT))
InstallFakeModules(device)
@@ -346,8 +348,8 @@
device.StartActivity(launch_intent)
device_utils.DeviceUtils.parallel(devices).pMap(launch)
if wait_for_java_debugger:
- print ('Waiting for debugger to attach to process: ' +
- _Colorize(debug_process_name, colorama.Fore.YELLOW))
+ print('Waiting for debugger to attach to process: ' +
+ _Colorize(debug_process_name, colorama.Fore.YELLOW))
def _ChangeFlags(devices, argv, command_line_flags_file):
@@ -399,8 +401,8 @@
if target_cpu:
cmd.append('--target-arch=%s' % _TargetCpuToTargetArch(target_cpu))
logging.warning('Running: %s', ' '.join(pipes.quote(x) for x in cmd))
- print _Colorize(
- 'All subsequent output is from adb_gdb script.', colorama.Fore.YELLOW)
+ print(_Colorize('All subsequent output is from adb_gdb script.',
+ colorama.Fore.YELLOW))
os.execv(gdb_script_path, cmd)
@@ -431,13 +433,12 @@
all_results = parallel_devices.pMap(mem_usage_helper).pGet(None)
for result in _PrintPerDeviceOutput(devices, all_results):
if not result:
- print 'No processes found.'
+ print('No processes found.')
else:
for name, usage in sorted(result):
- print _Colorize(
- '==== Output of "dumpsys meminfo %s" ====' % name,
- colorama.Fore.GREEN)
- print usage
+ print(_Colorize('==== Output of "dumpsys meminfo %s" ====' % name,
+ colorama.Fore.GREEN))
+ print(usage)
def _DuHelper(device, path_spec, run_as=None):
@@ -609,15 +610,15 @@
compilation_filter)
def print_sizes(desc, sizes):
- print '%s: %d KiB' % (desc, sum(sizes.itervalues()))
+ print('%s: %d KiB' % (desc, sum(sizes.itervalues())))
for path, size in sorted(sizes.iteritems()):
- print ' %s: %s KiB' % (path, size)
+ print(' %s: %s KiB' % (path, size))
parallel_devices = device_utils.DeviceUtils.parallel(devices)
all_results = parallel_devices.pMap(disk_usage_helper).pGet(None)
for result in _PrintPerDeviceOutput(devices, all_results):
if not result:
- print 'APK is not installed.'
+ print('APK is not installed.')
continue
(data_dir_sizes, code_cache_sizes, apk_sizes, lib_sizes, odex_sizes,
@@ -634,7 +635,7 @@
if show_warning:
logging.warning('For a more realistic odex size, run:')
logging.warning(' %s compile-dex [speed|speed-profile]', sys.argv[0])
- print 'Total: %s KiB (%.1f MiB)' % (total, total / 1024.0)
+ print('Total: %s KiB (%.1f MiB)' % (total, total / 1024.0))
class _LogcatProcessor(object):
@@ -801,13 +802,13 @@
lambda d: _GetPackageProcesses(d, package_name)).pGet(None)
for processes in _PrintPerDeviceOutput(devices, all_processes):
if not processes:
- print 'No processes found.'
+ print('No processes found.')
else:
proc_map = collections.defaultdict(list)
for p in processes:
proc_map[p.name].append(str(p.pid))
for name, pids in sorted(proc_map.items()):
- print name, ','.join(pids)
+ print(name, ','.join(pids))
def _RunShell(devices, package_name, cmd):
@@ -817,7 +818,7 @@
cmd, run_as=package_name).pGet(None)
for output in _PrintPerDeviceOutput(devices, outputs):
for line in output:
- print line
+ print(line)
else:
adb_path = adb_wrapper.AdbWrapper.GetAdbPath()
cmd = [adb_path, '-s', devices[0].serial, 'shell']
@@ -825,9 +826,9 @@
if devices[0].build_version_sdk >= version_codes.NOUGAT:
cmd += ['-t', 'run-as', package_name]
else:
- print 'Upon entering the shell, run:'
- print 'run-as', package_name
- print
+ print('Upon entering the shell, run:')
+ print('run-as', package_name)
+ print()
os.execv(adb_path, cmd)
@@ -838,7 +839,7 @@
outputs = parallel_devices.RunShellCommand(cmd, timeout=120).pGet(None)
for output in _PrintPerDeviceOutput(devices, outputs):
for line in output:
- print line
+ print(line)
def _RunProfile(device, package_name, host_build_directory, pprof_out_path,
@@ -858,7 +859,7 @@
simpleperf.ConvertSimpleperfToPprof(host_simpleperf_out_path,
host_build_directory, pprof_out_path)
- print textwrap.dedent("""
+ print(textwrap.dedent("""
Profile data written to %(s)s.
To view profile as a call graph in browser:
@@ -868,7 +869,7 @@
pprof -top %(s)s
pprof has many useful customization options; `pprof --help` for details.
- """ % {'s': pprof_out_path})
+ """ % {'s': pprof_out_path}))
def _GenerateAvailableDevicesMessage(devices):
@@ -894,11 +895,11 @@
parallel_devices = device_utils.DeviceUtils.parallel(devices)
outputs = parallel_devices.pMap(flags_helper).pGet(None)
- print 'Existing flags per-device (via /data/local/tmp/{}):'.format(
- command_line_flags_file)
+ print('Existing flags per-device (via /data/local/tmp/{}):'.format(
+ command_line_flags_file))
for flags in _PrintPerDeviceOutput(devices, outputs, single_line=True):
quoted_flags = ' '.join(pipes.quote(f) for f in flags)
- print quoted_flags or 'No flags set.'
+ print(quoted_flags or 'No flags set.')
def _DeviceCachePath(device, output_directory):
@@ -1134,7 +1135,7 @@
all_devices_by_default = True
def Run(self):
- print _GenerateAvailableDevicesMessage(self.devices)
+ print(_GenerateAvailableDevicesMessage(self.devices))
class _PackageInfoCommand(_Command):
@@ -1148,12 +1149,12 @@
def Run(self):
# Format all (even ints) as strings, to handle cases where APIs return None
- print 'Package name: "%s"' % self.args.package_name
- print 'versionCode: %s' % self.apk_helper.GetVersionCode()
- print 'versionName: "%s"' % self.apk_helper.GetVersionName()
- print 'minSdkVersion: %s' % self.apk_helper.GetMinSdkVersion()
- print 'targetSdkVersion: %s' % self.apk_helper.GetTargetSdkVersion()
- print 'Supported ABIs: %r' % self.apk_helper.GetAbis()
+ print('Package name: "%s"' % self.args.package_name)
+ print('versionCode: %s' % self.apk_helper.GetVersionCode())
+ print('versionName: "%s"' % self.apk_helper.GetVersionName())
+ print('minSdkVersion: %s' % self.apk_helper.GetMinSdkVersion())
+ print('targetSdkVersion: %s' % self.apk_helper.GetTargetSdkVersion())
+ print('Supported ABIs: %r' % self.apk_helper.GetAbis())
class _InstallCommand(_Command):
diff --git a/build/android/asan_symbolize.py b/build/android/asan_symbolize.py
index 9f2e88a..9a9963e 100755
--- a/build/android/asan_symbolize.py
+++ b/build/android/asan_symbolize.py
@@ -4,6 +4,7 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
import collections
import optparse
@@ -105,9 +106,9 @@
# that usually one wants to display the last list item, not the first.
# The code below takes the first, is this the best choice here?
s = all_symbols[m.library][m.rel_address][0]
- print '%s%s %s %s' % (m.prefix, m.pos, s[0], s[1])
+ print('%s%s %s %s' % (m.prefix, m.pos, s[0], s[1]))
else:
- print log_line.raw
+ print(log_line.raw)
def main():
diff --git a/build/android/binary_size/apk_downloader.py b/build/android/binary_size/apk_downloader.py
index aa7d12fd..12898343 100755
--- a/build/android/binary_size/apk_downloader.py
+++ b/build/android/binary_size/apk_downloader.py
@@ -3,6 +3,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import argparse
import os
import sys
@@ -38,10 +40,10 @@
sha1_path = apk_path + '.sha1'
base_url = os.path.join(bucket, builder, milestone)
if os.path.exists(apk_path):
- print '%s already exists' % apk_path
+ print('%s already exists' % apk_path)
return apk_path
elif not os.path.exists(sha1_path):
- print 'Skipping %s, file not found' % sha1_path
+ print('Skipping %s, file not found' % sha1_path)
return None
else:
download_from_google_storage.download_from_google_storage(
diff --git a/build/android/diff_resource_sizes.py b/build/android/diff_resource_sizes.py
index 8066844..eefb6cd 100755
--- a/build/android/diff_resource_sizes.py
+++ b/build/android/diff_resource_sizes.py
@@ -5,6 +5,8 @@
"""Runs resource_sizes.py on two apks and outputs the diff."""
+from __future__ import print_function
+
import argparse
import json
import logging
@@ -152,7 +154,7 @@
try:
subprocess.check_output(base_args, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
- print e.output
+ print(e.output)
raise
diff_args = shared_args + ['--output-dir', diff_dir, args.diff_apk]
@@ -161,7 +163,7 @@
try:
subprocess.check_output(diff_args, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
- print e.output
+ print(e.output)
raise
# Combine the separate results
diff --git a/build/android/dump_apk_resource_strings.py b/build/android/dump_apk_resource_strings.py
index 51e01f39..b57db50 100755
--- a/build/android/dump_apk_resource_strings.py
+++ b/build/android/dump_apk_resource_strings.py
@@ -6,6 +6,8 @@
"""A script to parse and dump localized strings in resource.arsc files."""
+from __future__ import print_function
+
import argparse
import collections
import contextlib
@@ -207,13 +209,13 @@
else:
# Sanity check: the resource name should be the same for all chunks.
# Resource ID is redefined with a different name!!
- print 'WARNING: Resource key ignored (%s, should be %s)' % (
- res_name, self.res_name)
+ print('WARNING: Resource key ignored (%s, should be %s)' %
+ (res_name, self.res_name))
if self.res_values.setdefault(res_config, res_value) is not res_value:
- print 'WARNING: Duplicate value definition for [config %s]: %s ' \
+ print('WARNING: Duplicate value definition for [config %s]: %s ' \
'(already has %s)' % (
- res_config, res_value, self.res_values[res_config])
+ res_config, res_value, self.res_values[res_config]))
def ToStringList(self, res_id):
"""Convert entry to string list for human-friendly output."""
diff --git a/build/android/generate_emma_html.py b/build/android/generate_emma_html.py
index dab3992..6260c249d 100755
--- a/build/android/generate_emma_html.py
+++ b/build/android/generate_emma_html.py
@@ -6,6 +6,8 @@
"""Aggregates EMMA coverage files to produce html output."""
+from __future__ import print_function
+
import fnmatch
import json
import optparse
@@ -61,8 +63,8 @@
# Filter out zero-length files. These are created by emma_instr.py when a
# target has no classes matching the coverage filter.
metadata_files = [f for f in metadata_files if os.path.getsize(f)]
- print 'Found coverage files: %s' % str(coverage_files)
- print 'Found metadata files: %s' % str(metadata_files)
+ print('Found coverage files: %s' % str(coverage_files))
+ print('Found metadata files: %s' % str(metadata_files))
sources = []
for f in metadata_files:
diff --git a/build/android/gradle/gn_to_cmake.py b/build/android/gradle/gn_to_cmake.py
index dd6c132..d3e80ae 100755
--- a/build/android/gradle/gn_to_cmake.py
+++ b/build/android/gradle/gn_to_cmake.py
@@ -16,6 +16,8 @@
The first is recommended, as it will auto-update.
"""
+from __future__ import print_function
+
import functools
import json
import posixpath
@@ -513,8 +515,8 @@
out.write('\n')
if target.cmake_type is None:
- print 'Target {} has unknown target type {}, skipping.'.format(
- target.gn_name, target.gn_type)
+ print('Target {} has unknown target type {}, skipping.'.format(
+ target.gn_name, target.gn_type))
return
SetVariable(out, 'target', target.cmake_name)
@@ -672,7 +674,7 @@
def main():
if len(sys.argv) != 2:
- print 'Usage: ' + sys.argv[0] + ' <json_file_name>'
+ print('Usage: ' + sys.argv[0] + ' <json_file_name>')
exit(1)
json_path = sys.argv[1]
diff --git a/build/android/gyp/assert_static_initializers.py b/build/android/gyp/assert_static_initializers.py
index 019bafa..a03ca1c 100755
--- a/build/android/gyp/assert_static_initializers.py
+++ b/build/android/gyp/assert_static_initializers.py
@@ -5,6 +5,8 @@
"""Checks the number of static initializers in an APK's library."""
+from __future__ import print_function
+
import argparse
import os
import re
@@ -54,7 +56,7 @@
_VerifyLibBuildIdsMatch(tool_prefix, unzipped_so, so_with_symbols_path)
sis, _ = _GetStaticInitializers(so_with_symbols_path, tool_prefix)
for si in sis:
- print si
+ print(si)
# Mostly copied from //infra/scripts/legacy/scripts/slave/chromium/sizes.py.
@@ -132,24 +134,24 @@
si_count = _AnalyzeStaticInitializers(args.apk, args.tool_prefix, False, '.',
ignored_libs)
if si_count != args.expected_count:
- print 'Expected {} static initializers, but found {}.'.format(
- args.expected_count, si_count)
+ print('Expected {} static initializers, but found {}.'.format(
+ args.expected_count, si_count))
if args.expected_count > si_count:
- print 'You have removed one or more static initializers. Thanks!'
- print 'To fix the build, update the expectation in:'
- print ' //chrome/android/static_initializers.gni'
+ print('You have removed one or more static initializers. Thanks!')
+ print('To fix the build, update the expectation in:')
+ print(' //chrome/android/static_initializers.gni')
else:
- print 'Dumping static initializers via dump-static-initializers.py:'
+ print('Dumping static initializers via dump-static-initializers.py:')
sys.stdout.flush()
_AnalyzeStaticInitializers(args.apk, args.tool_prefix, True, '.',
ignored_libs)
- print
- print 'If the above list is not useful, consider listing them with:'
- print ' //tools/binary_size/diagnose_bloat.py'
- print
- print 'For more information:'
- print (' https://chromium.googlesource.com/chromium/src/+/master/docs/'
- 'static_initializers.md')
+ print()
+ print('If the above list is not useful, consider listing them with:')
+ print(' //tools/binary_size/diagnose_bloat.py')
+ print()
+ print('For more information:')
+ print(' https://chromium.googlesource.com/chromium/src/+/master/docs/'
+ 'static_initializers.md')
sys.exit(1)
if args.touch:
diff --git a/build/android/gyp/copy_ex.py b/build/android/gyp/copy_ex.py
index 48d1b26..8451555e 100755
--- a/build/android/gyp/copy_ex.py
+++ b/build/android/gyp/copy_ex.py
@@ -6,6 +6,8 @@
"""Copies files to a directory."""
+from __future__ import print_function
+
import filecmp
import itertools
import optparse
@@ -53,8 +55,8 @@
for f in files:
if os.path.isdir(f) and not options.clear:
- print ('To avoid stale files you must use --clear when copying '
- 'directories')
+ print('To avoid stale files you must use --clear when copying '
+ 'directories')
sys.exit(-1)
CopyFile(f, options.dest, deps)
@@ -74,7 +76,7 @@
for src, dest in itertools.izip(src_files, dest_files):
if os.path.isdir(src):
- print ('renaming diretory is not supported.')
+ print('renaming diretory is not supported.')
sys.exit(-1)
else:
CopyFile(src, os.path.join(options.dest, dest), deps)
diff --git a/build/android/gyp/create_stack_script.py b/build/android/gyp/create_stack_script.py
index 6ccdc38..10c150d 100755
--- a/build/android/gyp/create_stack_script.py
+++ b/build/android/gyp/create_stack_script.py
@@ -17,6 +17,8 @@
#
# This file was generated by build/android/gyp/create_stack_script.py
+ from __future__ import print_function
+
import os
import sys
@@ -29,7 +31,7 @@
for arg, path in script_path_args:
script_args.extend([arg, resolve(path)])
script_cmd = [script_path] + script_args + argv
- print ' '.join(script_cmd)
+ print(' '.join(script_cmd))
os.execv(script_path, script_cmd)
if __name__ == '__main__':
diff --git a/build/android/gyp/emma_instr.py b/build/android/gyp/emma_instr.py
index cbe913eb..008a6cc 100755
--- a/build/android/gyp/emma_instr.py
+++ b/build/android/gyp/emma_instr.py
@@ -17,6 +17,8 @@
Also removes any stale coverage files.
"""
+from __future__ import print_function
+
import collections
import json
import optparse
@@ -121,8 +123,8 @@
for s in source_dirs:
abs_source = os.path.abspath(s)
if abs_source[:len(src_root)] != src_root:
- print ('Error: found source directory not under repository root: %s %s'
- % (abs_source, src_root))
+ print('Error: found source directory not under repository root: %s %s' %
+ (abs_source, src_root))
return 1
rel_source = os.path.relpath(abs_source, src_root)
diff --git a/build/android/gyp/find.py b/build/android/gyp/find.py
index a9f1d49..a78bc83 100755
--- a/build/android/gyp/find.py
+++ b/build/android/gyp/find.py
@@ -7,6 +7,8 @@
"""Finds files in directories.
"""
+from __future__ import print_function
+
import fnmatch
import optparse
import os
@@ -20,11 +22,12 @@
for d in directories:
if not os.path.exists(d):
- print >> sys.stderr, '%s does not exist' % d
+ print('%s does not exist' % d, file=sys.stderr)
return 1
for root, _, filenames in os.walk(d):
for f in fnmatch.filter(filenames, options.pattern):
- print os.path.join(root, f)
+ print(os.path.join(root, f))
+
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
diff --git a/build/android/gyp/lint.py b/build/android/gyp/lint.py
index b2f90c7e..77caf296 100755
--- a/build/android/gyp/lint.py
+++ b/build/android/gyp/lint.py
@@ -6,6 +6,7 @@
"""Runs Android's lint tool."""
+from __future__ import print_function
import argparse
import os
@@ -61,7 +62,7 @@
dom = minidom.parse(result_path)
issues = dom.getElementsByTagName('issue')
if not silent:
- print >> sys.stderr
+ print(file=sys.stderr)
for issue in issues:
issue_id = issue.attributes['id'].value
message = issue.attributes['message'].value
@@ -73,11 +74,11 @@
else:
# Issues in class files don't have a line number.
error = '%s %s: %s [warning]' % (path, message, issue_id)
- print >> sys.stderr, error.encode('utf-8')
+ print(error.encode('utf-8'), file=sys.stderr)
for attr in ['errorLine1', 'errorLine2']:
error_line = issue.getAttribute(attr)
if error_line:
- print >> sys.stderr, error_line.encode('utf-8')
+ print(error_line.encode('utf-8'), file=sys.stderr)
return len(issues)
with build_utils.TempDir() as temp_dir:
@@ -166,7 +167,7 @@
# classpath is necessary for most source-level checks.
with open(os.path.join(project_dir, 'project.properties'), 'w') \
as propfile:
- print >> propfile, 'target=android-{}'.format(android_sdk_version)
+ print('target=android-{}'.format(android_sdk_version), file=propfile)
# Put the manifest in a temporary directory in order to avoid lint detecting
# sibling res/ and src/ directories (which should be pass explicitly if they
@@ -222,10 +223,10 @@
num_issues = _ParseAndShowResultFile()
except Exception: # pylint: disable=broad-except
if not silent:
- print 'Lint created unparseable xml file...'
- print 'File contents:'
+ print('Lint created unparseable xml file...')
+ print('File contents:')
with open(result_path) as f:
- print f.read()
+ print(f.read())
if can_fail_build:
traceback.print_exc()
if can_fail_build:
@@ -243,7 +244,7 @@
' please refer to %s\n' %
(num_issues, _RebasePath(result_path), _LINT_MD_URL))
if not silent:
- print >> sys.stderr, msg
+ print(msg, file=sys.stderr)
if can_fail_build:
raise Exception('Lint failed.')
diff --git a/build/android/gyp/write_build_config.py b/build/android/gyp/write_build_config.py
index cb379cc..880f2c9d 100755
--- a/build/android/gyp/write_build_config.py
+++ b/build/android/gyp/write_build_config.py
@@ -552,6 +552,8 @@
--------------- END_MARKDOWN ---------------------------------------------------
"""
+from __future__ import print_function
+
import collections
import itertools
import json
diff --git a/build/android/lighttpd_server.py b/build/android/lighttpd_server.py
index c77d740..42fbcdbe6 100755
--- a/build/android/lighttpd_server.py
+++ b/build/android/lighttpd_server.py
@@ -10,6 +10,8 @@
lighttpd_server PATH_TO_DOC_ROOT
"""
+from __future__ import print_function
+
import codecs
import contextlib
import httplib
@@ -105,8 +107,8 @@
self.process.close()
if self.fixed_port or 'in use' not in server_error:
- print 'Client error:', client_error
- print 'Server error:', server_error
+ print('Client error:', client_error)
+ print('Server error:', server_error)
return False
self.port = self._GetRandomPort()
return True
@@ -249,7 +251,7 @@
raw_input('Server running at http://127.0.0.1:%s -'
' press Enter to exit it.' % server.port)
else:
- print 'Server exit code:', server.process.exitstatus
+ print('Server exit code:', server.process.exitstatus)
finally:
server.ShutdownHttpServer()
diff --git a/build/android/lint/suppress.py b/build/android/lint/suppress.py
index a3719c1..e1b30c82 100755
--- a/build/android/lint/suppress.py
+++ b/build/android/lint/suppress.py
@@ -8,6 +8,7 @@
# pylint: disable=no-member
+from __future__ import print_function
import argparse
import collections
@@ -49,7 +50,7 @@
def _ParseConfigFile(config_path):
- print 'Parsing %s' % config_path
+ print('Parsing %s' % config_path)
issues_dict = {}
dom = minidom.parse(config_path)
for issue in dom.getElementsByTagName('issue'):
@@ -71,7 +72,7 @@
def _ParseAndMergeResultFile(result_path, issues_dict):
- print 'Parsing and merging %s' % result_path
+ print('Parsing and merging %s' % result_path)
dom = minidom.parse(result_path)
for issue in dom.getElementsByTagName('issue'):
issue_id = issue.attributes['id'].value
@@ -98,7 +99,7 @@
if issue.severity:
issue_element.attributes['severity'] = issue.severity
if issue.severity == 'ignore':
- print 'Warning: [%s] is suppressed globally.' % issue_id
+ print('Warning: [%s] is suppressed globally.' % issue_id)
else:
for path in sorted(issue.paths):
ignore_element = new_dom.createElement('ignore')
@@ -112,7 +113,7 @@
with open(config_path, 'w') as f:
f.write(new_dom.toprettyxml(indent=' ', encoding='utf-8'))
- print 'Updated %s' % config_path
+ print('Updated %s' % config_path)
def _Suppress(config_path, result_path):
diff --git a/build/android/pylib/instrumentation/instrumentation_parser.py b/build/android/pylib/instrumentation/instrumentation_parser.py
index aa78e9e..8605178 100644
--- a/build/android/pylib/instrumentation/instrumentation_parser.py
+++ b/build/android/pylib/instrumentation/instrumentation_parser.py
@@ -39,11 +39,11 @@
for code, bundle in parser.IterStatus():
# do something with each instrumentation status
- print 'status:', code, bundle
+ print('status:', code, bundle)
# do something with the final instrumentation result
code, bundle = parser.GetResult()
- print 'result:', code, bundle
+ print('result:', code, bundle)
Args:
stream: a sequence of lines as produced by the raw output of an
diff --git a/build/android/pylib/linker/test_case.py b/build/android/pylib/linker/test_case.py
index 871da89..ee1b998 100644
--- a/build/android/pylib/linker/test_case.py
+++ b/build/android/pylib/linker/test_case.py
@@ -35,6 +35,8 @@
"""
# pylint: disable=R0201
+from __future__ import print_function
+
import logging
import re
@@ -158,7 +160,7 @@
A base_test_result.TestRunResult() instance.
"""
margin = 8
- print '[ %-*s ] %s' % (margin, 'RUN', self.tagged_name)
+ print('[ %-*s ] %s' % (margin, 'RUN', self.tagged_name))
logging.info('Running linker test: %s', self.tagged_name)
command_line_flags = ''
@@ -174,7 +176,7 @@
result_text = 'FAILED'
elif status == ResultType.TIMEOUT:
result_text = 'TIMEOUT'
- print '[ %*s ] %s' % (margin, result_text, self.tagged_name)
+ print('[ %*s ] %s' % (margin, result_text, self.tagged_name))
return base_test_result.BaseTestResult(self.tagged_name, status, log=logs)
diff --git a/build/android/pylib/perf/perf_test_instance.py b/build/android/pylib/perf/perf_test_instance.py
index 49d75e4..5c64e124 100644
--- a/build/android/pylib/perf/perf_test_instance.py
+++ b/build/android/pylib/perf/perf_test_instance.py
@@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import json
import logging
import os
@@ -134,7 +136,7 @@
for i in xrange(len(persisted_outputs)):
output_formatted += '\n\nOutput from run #%d:\n\n%s' % (
i, persisted_outputs[i])
- print output_formatted
+ print(output_formatted)
if self.output_chartjson_data:
with file(self.output_chartjson_data, 'w') as f:
diff --git a/build/android/pylib/results/presentation/standard_gtest_merge.py b/build/android/pylib/results/presentation/standard_gtest_merge.py
index 5dba4df..58a29366c 100755
--- a/build/android/pylib/results/presentation/standard_gtest_merge.py
+++ b/build/android/pylib/results/presentation/standard_gtest_merge.py
@@ -4,6 +4,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import argparse
import json
import os
@@ -42,16 +44,17 @@
# name form, not in the number form.
state = result.get('state')
if state == u'BOT_DIED':
- print >> sys.stderr, 'Shard #%d had a Swarming internal failure' % index
+ print(
+ 'Shard #%d had a Swarming internal failure' % index, file=sys.stderr)
elif state == u'EXPIRED':
- print >> sys.stderr, 'There wasn\'t enough capacity to run your test'
+ print('There wasn\'t enough capacity to run your test', file=sys.stderr)
elif state == u'TIMED_OUT':
- print >> sys.stderr, (
- 'Test runtime exceeded allocated time'
- 'Either it ran for too long (hard timeout) or it didn\'t produce '
- 'I/O for an extended period of time (I/O timeout)')
+ print('Test runtime exceeded allocated time'
+ 'Either it ran for too long (hard timeout) or it didn\'t produce '
+ 'I/O for an extended period of time (I/O timeout)',
+ file=sys.stderr)
elif state != u'COMPLETED':
- print >> sys.stderr, 'Invalid Swarming task state: %s' % state
+ print('Invalid Swarming task state: %s' % state, file=sys.stderr)
json_data, err_msg = load_shard_json(index, result.get('task_id'),
jsons_to_merge)
@@ -66,14 +69,14 @@
merged['per_iteration_data'], json_data.get('per_iteration_data', []))
else:
merged['missing_shards'].append(index)
- print >> sys.stderr, 'No result was found: %s' % err_msg
+ print('No result was found: %s' % err_msg, file=sys.stderr)
# If some shards are missing, make it known. Continue parsing anyway. Step
# should be red anyway, since swarming.py return non-zero exit code in that
# case.
if merged['missing_shards']:
as_str = ', '.join([str(shard) for shard in merged['missing_shards']])
- print >> sys.stderr, ('some shards did not complete: %s' % as_str)
+ print('some shards did not complete: %s' % as_str, file=sys.stderr)
# Not all tests run, combined JSON summary can not be trusted.
merged['global_tags'].add('UNRELIABLE_RESULTS')
@@ -106,10 +109,10 @@
os.path.basename(os.path.dirname(j)) == task_id))]
if not matching_json_files:
- print >> sys.stderr, 'shard %s test output missing' % index
+ print('shard %s test output missing' % index, file=sys.stderr)
return (None, 'shard %s test output was missing' % index)
elif len(matching_json_files) > 1:
- print >> sys.stderr, 'duplicate test output for shard %s' % index
+ print('duplicate test output for shard %s' % index, file=sys.stderr)
return (None, 'shard %s test output was duplicated' % index)
path = matching_json_files[0]
@@ -117,15 +120,17 @@
try:
filesize = os.stat(path).st_size
if filesize > OUTPUT_JSON_SIZE_LIMIT:
- print >> sys.stderr, 'output.json is %d bytes. Max size is %d' % (
- filesize, OUTPUT_JSON_SIZE_LIMIT)
+ print(
+ 'output.json is %d bytes. Max size is %d' % (filesize,
+ OUTPUT_JSON_SIZE_LIMIT),
+ file=sys.stderr)
return (None, 'shard %s test output exceeded the size limit' % index)
with open(path) as f:
return (json.load(f), None)
except (IOError, ValueError, OSError) as e:
- print >> sys.stderr, 'Missing or invalid gtest JSON file: %s' % path
- print >> sys.stderr, '%s: %s' % (type(e).__name__, e)
+ print('Missing or invalid gtest JSON file: %s' % path, file=sys.stderr)
+ print('%s: %s' % (type(e).__name__, e), file=sys.stderr)
return (None, 'shard %s test output was missing or invalid' % index)
diff --git a/build/android/pylib/results/presentation/test_results_presentation.py b/build/android/pylib/results/presentation/test_results_presentation.py
index 82d6c88..ff100f0e 100755
--- a/build/android/pylib/results/presentation/test_results_presentation.py
+++ b/build/android/pylib/results/presentation/test_results_presentation.py
@@ -4,6 +4,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import argparse
import collections
import contextlib
@@ -463,8 +465,8 @@
if len(args.positional) == 0 and args.json_file is None:
if args.output_json:
- with open(args.output_json, 'w') as f:
- json.dump({}, f)
+ with open(args.output_json, 'w') as f:
+ json.dump({}, f)
return
elif len(args.positional) != 0 and args.json_file:
raise parser.error('Exactly one of args.positional and '
@@ -533,10 +535,10 @@
with open(args.output_json, 'w') as f:
json.dump(json_object, f)
else:
- print 'Result Details: %s' % result_details_link
+ print('Result Details: %s' % result_details_link)
if ui_screenshot_set_link:
- print 'UI Screenshots %s' % ui_screenshot_link
+ print('UI Screenshots %s' % ui_screenshot_link)
if __name__ == '__main__':
diff --git a/build/android/pylib/results/report_results.py b/build/android/pylib/results/report_results.py
index e886b72..56eefac4 100644
--- a/build/android/pylib/results/report_results.py
+++ b/build/android/pylib/results/report_results.py
@@ -4,6 +4,8 @@
"""Module containing utility functions for reporting results."""
+from __future__ import print_function
+
import logging
import os
import re
@@ -22,16 +24,19 @@
log_file_path, re.sub(r'\W', '_', test_type).lower() + '.log')
if not os.path.exists(full_file_name):
with open(full_file_name, 'w') as log_file:
- print >> log_file, '\n%s results for %s build %s:' % (
- test_type, os.environ.get('BUILDBOT_BUILDERNAME'),
- os.environ.get('BUILDBOT_BUILDNUMBER'))
+ print(
+ '\n%s results for %s build %s:' %
+ (test_type, os.environ.get('BUILDBOT_BUILDERNAME'),
+ os.environ.get('BUILDBOT_BUILDNUMBER')),
+ file=log_file)
logging.info('Writing results to %s.', full_file_name)
logging.info('Writing results to %s.', full_file_name)
with open(full_file_name, 'a') as log_file:
shortened_suite_name = suite_name[:25] + (suite_name[25:] and '...')
- print >> log_file, '%s%s' % (shortened_suite_name.ljust(30),
- results.GetShortForm())
+ print(
+ '%s%s' % (shortened_suite_name.ljust(30), results.GetShortForm()),
+ file=log_file)
def _LogToFlakinessDashboard(results, test_type, test_package,
diff --git a/build/android/pylib/symbols/apk_lib_dump.py b/build/android/pylib/symbols/apk_lib_dump.py
index 956ee07..ba87026 100755
--- a/build/android/pylib/symbols/apk_lib_dump.py
+++ b/build/android/pylib/symbols/apk_lib_dump.py
@@ -22,6 +22,8 @@
(0x<start-offset>, 0x<end-offset>, 0x<file-size>, <file-path>),
"""
+from __future__ import print_function
+
import argparse
import os
import sys
@@ -46,11 +48,11 @@
lib_map = apk_native_libs.ApkNativeLibraries(apk_reader)
for lib_path, file_offset, file_size in lib_map.GetDumpList():
if args.format == 'python':
- print '(0x%08x, 0x%08x, 0x%08x, \'%s\'),' % (
- file_offset, file_offset + file_size, file_size, lib_path)
+ print('(0x%08x, 0x%08x, 0x%08x, \'%s\'),' %
+ (file_offset, file_offset + file_size, file_size, lib_path))
else:
- print '0x%08x 0x%08x 0x%08x %s' % (
- file_offset, file_offset + file_size, file_size, lib_path)
+ print('0x%08x 0x%08x 0x%08x %s' % (file_offset, file_offset + file_size,
+ file_size, lib_path))
return 0
diff --git a/build/android/pylib/symbols/mock_addr2line/mock_addr2line b/build/android/pylib/symbols/mock_addr2line/mock_addr2line
index cd58f56d..8b2a723 100755
--- a/build/android/pylib/symbols/mock_addr2line/mock_addr2line
+++ b/build/android/pylib/symbols/mock_addr2line/mock_addr2line
@@ -9,6 +9,8 @@
original address (so it is easy to double-check consistency in unittests).
"""
+from __future__ import print_function
+
import optparse
import os
import posixpath
@@ -36,8 +38,8 @@
# An empty line should generate '??,??:0' (is used as marker for inlines).
if line == '\n':
- print '??'
- print '??:0'
+ print('??')
+ print('??:0')
sys.stdout.flush()
continue
@@ -50,27 +52,27 @@
# Addresses < 1M will return good mock symbol information.
if addr < 1024 * 1024:
- print 'mock_sym_for_addr_%d' % addr
- print 'mock_src/%s.c:%d' % (lib_file_name, addr)
+ print('mock_sym_for_addr_%d' % addr)
+ print('mock_src/%s.c:%d' % (lib_file_name, addr))
# Addresses 1M <= x < 2M will return symbols with a name but a missing path.
elif addr < 2 * 1024 * 1024:
- print 'mock_sym_for_addr_%d' % addr
- print '??:0'
+ print('mock_sym_for_addr_%d' % addr)
+ print('??:0')
# Addresses 2M <= x < 3M will return unknown symbol information.
elif addr < 3 * 1024 * 1024:
- print '??'
- print '??'
+ print('??')
+ print('??')
# Addresses 3M <= x < 4M will return inlines.
elif addr < 4 * 1024 * 1024:
- print 'mock_sym_for_addr_%d_inner' % addr
- print 'mock_src/%s.c:%d' % (lib_file_name, addr)
- print 'mock_sym_for_addr_%d_middle' % addr
- print 'mock_src/%s.c:%d' % (lib_file_name, addr)
- print 'mock_sym_for_addr_%d_outer' % addr
- print 'mock_src/%s.c:%d' % (lib_file_name, addr)
+ print('mock_sym_for_addr_%d_inner' % addr)
+ print('mock_src/%s.c:%d' % (lib_file_name, addr))
+ print('mock_sym_for_addr_%d_middle' % addr)
+ print('mock_src/%s.c:%d' % (lib_file_name, addr))
+ print('mock_sym_for_addr_%d_outer' % addr)
+ print('mock_src/%s.c:%d' % (lib_file_name, addr))
sys.stdout.flush()
diff --git a/build/android/pylib/symbols/symbol_utils.py b/build/android/pylib/symbols/symbol_utils.py
index e4e3faa..dea3c63 100644
--- a/build/android/pylib/symbols/symbol_utils.py
+++ b/build/android/pylib/symbols/symbol_utils.py
@@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import bisect
import collections
import logging
@@ -516,12 +518,12 @@
def Dump(self):
"""Print memory map for debugging."""
- print 'MEMORY MAP ['
+ print('MEMORY MAP [')
for t in self._addr_map:
- print '[%08x-%08x %08x %08x %s]' % (
- t.addr_start, t.addr_start + t.file_size, t.file_size, t.file_offset,
- t.file_path)
- print '] MEMORY MAP'
+ print('[%08x-%08x %08x %08x %s]' %
+ (t.addr_start, t.addr_start + t.file_size, t.file_size,
+ t.file_offset, t.file_path))
+ print('] MEMORY MAP')
def FindSectionForAddress(self, addr):
"""Find the map section corresponding to a specific memory address.
diff --git a/build/android/pylib/utils/argparse_utils.py b/build/android/pylib/utils/argparse_utils.py
index e456d9d..06544a2 100644
--- a/build/android/pylib/utils/argparse_utils.py
+++ b/build/android/pylib/utils/argparse_utils.py
@@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import argparse
@@ -42,7 +44,7 @@
self._help_text = custom_help_text
def __call__(self, parser, namespace, values, option_string=None):
- print self._help_text
+ print(self._help_text)
parser.exit()
@staticmethod
diff --git a/build/android/pylib/valgrind_tools.py b/build/android/pylib/valgrind_tools.py
index 4c27b08..9fdaddb7 100644
--- a/build/android/pylib/valgrind_tools.py
+++ b/build/android/pylib/valgrind_tools.py
@@ -4,6 +4,8 @@
# pylint: disable=R0201
+from __future__ import print_function
+
import glob
import logging
import os.path
@@ -106,8 +108,8 @@
if ctor:
return ctor(device)
else:
- print 'Unknown tool %s, available tools: %s' % (
- tool_name, ', '.join(sorted(TOOL_REGISTRY.keys())))
+ print('Unknown tool %s, available tools: %s' % (tool_name, ', '.join(
+ sorted(TOOL_REGISTRY.keys()))))
sys.exit(1)
def PushFilesForTool(tool_name, device):
@@ -124,6 +126,6 @@
if clazz:
clazz.CopyFiles(device)
else:
- print 'Unknown tool %s, available tools: %s' % (
- tool_name, ', '.join(sorted(TOOL_REGISTRY.keys())))
+ print('Unknown tool %s, available tools: %s' % (tool_name, ', '.join(
+ sorted(TOOL_REGISTRY.keys()))))
sys.exit(1)
diff --git a/build/android/stacktrace/stackwalker.py b/build/android/stacktrace/stackwalker.py
index db54354..5fbab339 100755
--- a/build/android/stacktrace/stackwalker.py
+++ b/build/android/stacktrace/stackwalker.py
@@ -4,6 +4,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import argparse
import os
import re
@@ -95,7 +97,7 @@
def _PrintAndLog(line, fp):
if fp:
fp.write('%s\n' % line)
- print line
+ print(line)
def main():
@@ -105,7 +107,7 @@
micro_dumps = GetMicroDumps(args.stack_trace_path)
if not micro_dumps:
- print 'No microdump found. Exiting.'
+ print('No microdump found. Exiting.')
return 0
symbolized_dumps = []
diff --git a/build/apply_locales.py b/build/apply_locales.py
index 6af7280..fcd02eb 100755
--- a/build/apply_locales.py
+++ b/build/apply_locales.py
@@ -5,6 +5,8 @@
# TODO: remove this script when GYP has for loops
+from __future__ import print_function
+
import sys
import optparse
@@ -20,7 +22,7 @@
(options, arglist) = parser.parse_args(argv)
if len(arglist) < 3:
- print 'ERROR: need string and list of locales'
+ print('ERROR: need string and list of locales')
return 1
str_template = arglist[1]
@@ -39,7 +41,8 @@
# Quote each element so filename spaces don't mess up GYP's attempt to parse
# it into a list.
- print ' '.join(["'%s'" % x for x in results])
+ print(' '.join(["'%s'" % x for x in results]))
+
if __name__ == '__main__':
sys.exit(main(sys.argv))
diff --git a/build/check_gn_headers.py b/build/check_gn_headers.py
index 2de11b83..9bdbba8 100755
--- a/build/check_gn_headers.py
+++ b/build/check_gn_headers.py
@@ -9,6 +9,8 @@
dependency generated by the compiler, and report if they don't exist in GN.
"""
+from __future__ import print_function
+
import argparse
import json
import os
@@ -152,7 +154,7 @@
out = subprocess.check_output(cmd)
return 'no work to do.' in out
except Exception as e:
- print e
+ print(e)
return False
def ParseWhiteList(whitelist):
@@ -211,7 +213,7 @@
# Assume running on the bots. Silently skip this step.
# This is possible because "analyze" step can be wrong due to
# underspecified header files. See crbug.com/725877
- print dirty_msg
+ print(dirty_msg)
DumpJson([])
return 0
else:
@@ -250,7 +252,7 @@
if deps_err:
PrintError(deps_err)
if len(GetNonExistingFiles(d)) > 0:
- print 'Non-existing files in ninja deps:', GetNonExistingFiles(d)
+ print('Non-existing files in ninja deps:', GetNonExistingFiles(d))
PrintError('Found non-existing files in ninja deps. You should ' +
'build all in OUT_DIR.')
if len(d) == 0:
@@ -272,30 +274,30 @@
return 0
if len(missing) > 0:
- print '\nThe following files should be included in gn files:'
+ print('\nThe following files should be included in gn files:')
for i in missing:
- print i
+ print(i)
if len(nonexisting) > 0:
- print '\nThe following non-existing files should be removed from gn files:'
+ print('\nThe following non-existing files should be removed from gn files:')
for i in nonexisting:
- print i
+ print(i)
if args.verbose:
# Only get detailed obj dependency here since it is slower.
GetHeadersFromNinja(args.out_dir, False, d_q)
d, d_err = d_q.get()
- print '\nDetailed dependency info:'
+ print('\nDetailed dependency info:')
for f in missing:
- print f
+ print(f)
for cc in d[f]:
- print ' ', cc
+ print(' ', cc)
- print '\nMissing headers sorted by number of affected object files:'
+ print('\nMissing headers sorted by number of affected object files:')
count = {k: len(v) for (k, v) in d.iteritems()}
for f in sorted(count, key=count.get, reverse=True):
if f in missing:
- print count[f], f
+ print(count[f], f)
if args.json:
# Assume running on the bots. Temporarily return 0 before
diff --git a/build/check_return_value.py b/build/check_return_value.py
index c659d1e9..9caa15f 100755
--- a/build/check_return_value.py
+++ b/build/check_return_value.py
@@ -6,12 +6,14 @@
"""This program wraps an arbitrary command and prints "1" if the command ran
successfully."""
+from __future__ import print_function
+
import os
import subprocess
import sys
devnull = open(os.devnull, 'wb')
if not subprocess.call(sys.argv[1:], stdout=devnull, stderr=devnull):
- print 1
+ print(1)
else:
- print 0
+ print(0)
diff --git a/build/config/get_host_byteorder.py b/build/config/get_host_byteorder.py
index c8fcf1f..fc01d857 100755
--- a/build/config/get_host_byteorder.py
+++ b/build/config/get_host_byteorder.py
@@ -5,7 +5,8 @@
"""Get Byteorder of host architecture"""
+from __future__ import print_function
import sys
-print sys.byteorder
+print(sys.byteorder)
diff --git a/build/config/ios/find_signing_identity.py b/build/config/ios/find_signing_identity.py
index 7add474..19ab48b5 100644
--- a/build/config/ios/find_signing_identity.py
+++ b/build/config/ios/find_signing_identity.py
@@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import argparse
import os
import subprocess
@@ -44,4 +46,4 @@
os.environ['DEVELOPER_DIR'] = args.developer_dir
for identity in FindValidIdentity(args.identity_description):
- print identity
+ print(identity)
diff --git a/build/config/ios/write_framework_hmap.py b/build/config/ios/write_framework_hmap.py
index 8f6b143..08ea9e9e 100644
--- a/build/config/ios/write_framework_hmap.py
+++ b/build/config/ios/write_framework_hmap.py
@@ -2,14 +2,17 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import os
import struct
import sys
def Main(args):
if len(args) < 4:
- print >> sys.stderr, "Usage: %s output.hmap Foo.framework header1.h..." %\
- (args[0])
+ print(
+ "Usage: %s output.hmap Foo.framework header1.h..." % args[0],
+ file=sys.stderr)
return 1
(out, framework, all_headers) = args[1], args[2], args[3:]
diff --git a/build/config/linux/pkg-config.py b/build/config/linux/pkg-config.py
index e2bf766..930810b 100755
--- a/build/config/linux/pkg-config.py
+++ b/build/config/linux/pkg-config.py
@@ -3,6 +3,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import json
import os
import subprocess
@@ -54,7 +56,7 @@
# Compute the library path name based on the architecture.
arch = options.arch
if sysroot and not arch:
- print "You must specify an architecture via -a if using a sysroot."
+ print("You must specify an architecture via -a if using a sysroot.")
sys.exit(1)
libdir = sysroot + '/usr/' + options.system_libdir + '/pkgconfig'
@@ -108,7 +110,7 @@
# success. This allows us to "kind of emulate" a Linux build from other
# platforms.
if "linux" not in sys.platform:
- print "[[],[],[],[],[]]"
+ print("[[],[],[],[],[]]")
return 0
parser = OptionParser()
@@ -148,9 +150,9 @@
if not subprocess.call([options.pkg_config,
"--atleast-version=" + options.atleast_version] +
args):
- print "true"
+ print("true")
else:
- print "false"
+ print("false")
return 0
if options.version_as_components:
@@ -160,7 +162,7 @@
except:
sys.stderr.write('Error from pkg-config.\n')
return 1
- print json.dumps(list(map(int, version_string.strip().split("."))))
+ print(json.dumps(list(map(int, version_string.strip().split(".")))))
return 0
@@ -171,7 +173,7 @@
try:
libdir = subprocess.check_output(cmd)
except:
- print "Error from pkg-config."
+ print("Error from pkg-config.")
return 1
sys.stdout.write(libdir.strip())
return 0
@@ -183,7 +185,7 @@
try:
dridriverdir = subprocess.check_output(cmd)
except:
- print "Error from pkg-config."
+ print("Error from pkg-config.")
return 1
sys.stdout.write(dridriverdir.strip())
return
@@ -238,7 +240,7 @@
# Output a GN array, the first one is the cflags, the second are the libs. The
# JSON formatter prints GN compatible lists when everything is a list of
# strings.
- print json.dumps([includes, cflags, libs, lib_dirs])
+ print(json.dumps([includes, cflags, libs, lib_dirs]))
return 0
diff --git a/build/config/mac/compile_ib_files.py b/build/config/mac/compile_ib_files.py
index 281e554..cb6fa05 100644
--- a/build/config/mac/compile_ib_files.py
+++ b/build/config/mac/compile_ib_files.py
@@ -2,6 +2,7 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
import argparse
import logging
diff --git a/build/config/mac/sdk_info.py b/build/config/mac/sdk_info.py
index 46dcec8..249dcd56 100644
--- a/build/config/mac/sdk_info.py
+++ b/build/config/mac/sdk_info.py
@@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import argparse
import doctest
import itertools
@@ -94,4 +96,4 @@
value = settings[key]
if isinstance(value, str):
value = '"%s"' % value
- print '%s=%s' % (key, value)
+ print('%s=%s' % (key, value))
diff --git a/build/config/posix/sysroot_ld_path.py b/build/config/posix/sysroot_ld_path.py
index 7056207..5fe5623 100644
--- a/build/config/posix/sysroot_ld_path.py
+++ b/build/config/posix/sysroot_ld_path.py
@@ -8,14 +8,16 @@
# TODO(brettw) the build/linux/sysroot_ld_path.sh script should be rewritten in
# Python in this file.
+from __future__ import print_function
+
import subprocess
import sys
if len(sys.argv) != 3:
- print "Need two arguments"
+ print("Need two arguments")
sys.exit(1)
result = subprocess.check_output([sys.argv[1], sys.argv[2]]).strip()
result = result.replace(" ", "\n")
if result != "":
- print result
+ print(result)
diff --git a/build/copy_test_data_ios.py b/build/copy_test_data_ios.py
index 6f0302f..6a15ca2 100755
--- a/build/copy_test_data_ios.py
+++ b/build/copy_test_data_ios.py
@@ -5,6 +5,8 @@
"""Copies test data files or directories into a given output directory."""
+from __future__ import print_function
+
import optparse
import os
import shutil
@@ -95,10 +97,10 @@
try:
result = DoMain(argv[1:])
except WrongNumberOfArgumentsException, e:
- print >>sys.stderr, e
+ print(e, file=sys.stderr)
return 1
if result:
- print result
+ print(result)
return 0
if __name__ == '__main__':
diff --git a/build/detect_host_arch.py b/build/detect_host_arch.py
index 1c13aa6..cad0f4b 100755
--- a/build/detect_host_arch.py
+++ b/build/detect_host_arch.py
@@ -5,6 +5,8 @@
"""Outputs host CPU architecture in format recognized by gyp."""
+from __future__ import print_function
+
import platform
import re
import sys
@@ -50,4 +52,4 @@
return HostArch()
if __name__ == '__main__':
- print DoMain([])
+ print(DoMain([]))
diff --git a/build/extract_from_cab.py b/build/extract_from_cab.py
index 080370c..9695b96 100755
--- a/build/extract_from_cab.py
+++ b/build/extract_from_cab.py
@@ -5,6 +5,8 @@
"""Extracts a single file from a CAB archive."""
+from __future__ import print_function
+
import os
import shutil
import subprocess
@@ -17,12 +19,12 @@
out, _ = popen.communicate()
if popen.returncode:
# expand emits errors to stdout, so if we fail, then print that out.
- print out
+ print(out)
return popen.returncode
def main():
if len(sys.argv) != 4:
- print 'Usage: extract_from_cab.py cab_path archived_file output_dir'
+ print('Usage: extract_from_cab.py cab_path archived_file output_dir')
return 1
[cab_path, archived_file, output_dir] = sys.argv[1:]
diff --git a/build/find_depot_tools.py b/build/find_depot_tools.py
index 5c496e7..49a9138e 100755
--- a/build/find_depot_tools.py
+++ b/build/find_depot_tools.py
@@ -11,6 +11,8 @@
directory location.
"""
+from __future__ import print_function
+
import os
import sys
@@ -53,7 +55,7 @@
return i
previous_dir = root_dir
root_dir = os.path.dirname(root_dir)
- print >> sys.stderr, 'Failed to find depot_tools'
+ print('Failed to find depot_tools', file=sys.stderr)
return None
DEPOT_TOOLS_PATH = add_depot_tools_to_path()
@@ -65,7 +67,7 @@
def main():
if DEPOT_TOOLS_PATH is None:
return 1
- print DEPOT_TOOLS_PATH
+ print(DEPOT_TOOLS_PATH)
return 0
diff --git a/build/fix_gn_headers.py b/build/fix_gn_headers.py
index 01ff764e..71fb332b 100755
--- a/build/fix_gn_headers.py
+++ b/build/fix_gn_headers.py
@@ -10,6 +10,8 @@
Manual cleaning up is likely required afterwards.
"""
+from __future__ import print_function
+
import argparse
import os
import re
@@ -39,7 +41,7 @@
continue
if lines[linenr - 2] == new:
continue
- print ' ', gnfile, linenr, new
+ print(' ', gnfile, linenr, new)
matches.append((gnfile, linenr, new))
return matches
@@ -59,7 +61,7 @@
if not (filename.endswith('.h') or filename.endswith('.hh')):
continue
basename = os.path.basename(filename)
- print filename
+ print(filename)
cc = r'\b' + os.path.splitext(basename)[0] + r'\.(cc|cpp|mm)\b'
out, returncode = GitGrep('(/|")' + cc + '"')
if returncode != 0 or not out:
@@ -71,10 +73,10 @@
if len(matches) == 0:
continue
if len(matches) > 1:
- print '\n[WARNING] Ambiguous matching for', filename
+ print('\n[WARNING] Ambiguous matching for', filename)
for i in enumerate(matches, 1):
- print '%d: %s' % (i[0], i[1])
- print
+ print('%d: %s' % (i[0], i[1]))
+ print()
if skip_ambiguous:
continue
@@ -86,7 +88,7 @@
for match in matches:
gnfile, linenr, new = match
- print ' ', gnfile, linenr, new
+ print(' ', gnfile, linenr, new)
edits.setdefault(gnfile, {})[linenr] = new
for gnfile in edits:
@@ -111,7 +113,7 @@
"""
for filename in headers:
filename = filename.strip()
- print filename
+ print(filename)
dirname = os.path.dirname(filename)
while not os.path.exists(os.path.join(dirname, 'BUILD.gn')):
dirname = os.path.dirname(dirname)
@@ -121,12 +123,12 @@
lines = open(gnfile).read().splitlines()
matched = [i for i, l in enumerate(lines) if ' sources = [' in l]
if skip_ambiguous and len(matched) > 1:
- print '[WARNING] Multiple sources in', gnfile
+ print('[WARNING] Multiple sources in', gnfile)
continue
if len(matched) < 1:
continue
- print ' ', gnfile, rel
+ print(' ', gnfile, rel)
index = matched[0]
lines.insert(index + 1, '"%s",' % rel)
open(gnfile, 'w').write('\n'.join(lines) + '\n')
@@ -144,18 +146,18 @@
if not (filename.endswith('.h') or filename.endswith('.hh')):
continue
basename = os.path.basename(filename)
- print filename
+ print(filename)
out, returncode = GitGrep('(/|")' + basename + '"')
if returncode != 0 or not out:
unhandled.append(filename)
- print ' Not found'
+ print(' Not found')
continue
grep_lines = out.splitlines()
matches = []
for line in grep_lines:
gnfile, linenr, contents = line.split(':')
- print ' ', gnfile, linenr, contents
+ print(' ', gnfile, linenr, contents)
linenr = int(linenr)
lines = open(gnfile).read().splitlines()
assert contents in lines[linenr - 1]
@@ -164,10 +166,10 @@
if len(matches) == 0:
continue
if len(matches) > 1:
- print '\n[WARNING] Ambiguous matching for', filename
+ print('\n[WARNING] Ambiguous matching for', filename)
for i in enumerate(matches, 1):
- print '%d: %s' % (i[0], i[1])
- print
+ print('%d: %s' % (i[0], i[1]))
+ print()
if skip_ambiguous:
continue
@@ -179,7 +181,7 @@
for match in matches:
gnfile, linenr, contents = match
- print ' ', gnfile, linenr, contents
+ print(' ', gnfile, linenr, contents)
edits.setdefault(gnfile, set()).add(linenr)
for gnfile in edits:
diff --git a/build/fuchsia/device_target.py b/build/fuchsia/device_target.py
index a429c66..a036a7b1 100644
--- a/build/fuchsia/device_target.py
+++ b/build/fuchsia/device_target.py
@@ -4,6 +4,8 @@
"""Implements commands for running and interacting with Fuchsia on devices."""
+from __future__ import print_function
+
import boot_data
import filecmp
import logging
@@ -165,12 +167,12 @@
# Handle the output of "dev_finder list".
if len(name_host_pairs) > 1:
- print 'More than one device was discovered on the network.'
- print 'Use --node-name <name> to specify the device to use.'
- print '\nList of devices:'
+ print('More than one device was discovered on the network.')
+ print('Use --node-name <name> to specify the device to use.')
+ print('\nList of devices:')
for pair in name_host_pairs:
- print ' ' + pair[1]
- print
+ print(' ' + pair[1])
+ print()
raise Exception('Ambiguous target device specification.')
assert len(name_host_pairs) == 1
diff --git a/build/fuchsia/run_package.py b/build/fuchsia/run_package.py
index 638d3b7..6e3a5d2 100644
--- a/build/fuchsia/run_package.py
+++ b/build/fuchsia/run_package.py
@@ -5,6 +5,8 @@
"""Contains a helper function for deploying and executing a packaged
executable on a Target."""
+from __future__ import print_function
+
import common
import hashlib
import logging
@@ -146,7 +148,7 @@
line = rlist[0].readline()
if not line:
return
- print line.rstrip()
+ print(line.rstrip())
def RunPackage(output_dir, target, package_path, package_name,
@@ -207,7 +209,7 @@
output_stream = SymbolizerFilter(output_stream, build_ids_paths)
for next_line in output_stream:
- print next_line.rstrip()
+ print(next_line.rstrip())
process.wait()
if process.returncode == 0:
diff --git a/build/fuchsia/update_sdk.py b/build/fuchsia/update_sdk.py
index f7d6115..31a04c3 100755
--- a/build/fuchsia/update_sdk.py
+++ b/build/fuchsia/update_sdk.py
@@ -6,6 +6,8 @@
"""Updates the Fuchsia SDK to the given revision. Should be used in a 'hooks_os'
entry so that it only runs when .gclient's target_os includes 'fuchsia'."""
+from __future__ import print_function
+
import os
import re
import shutil
@@ -59,8 +61,9 @@
# If both files are empty, return an error.
if not sdk_hash and not extra_sdk_hash:
- print >>sys.stderr, 'No SHA1 found in {} or {}'.format(
- hash_file, extra_hash_file)
+ print(
+ 'No SHA1 found in {} or {}'.format(hash_file, extra_hash_file),
+ file=sys.stderr)
return 1
# Return the newer SDK based on the generation number.
@@ -77,7 +80,7 @@
def EnsureDirExists(path):
if not os.path.exists(path):
- print 'Creating directory %s' % path
+ print('Creating directory %s' % path)
os.makedirs(path)
@@ -85,7 +88,7 @@
def Cleanup(path):
hash_file = os.path.join(path, '.hash')
if os.path.exists(hash_file):
- print 'Removing old SDK from %s.' % path
+ print('Removing old SDK from %s.' % path)
for d in SDK_SUBDIRS:
to_remove = os.path.join(path, d)
if os.path.isdir(to_remove):
@@ -105,7 +108,7 @@
def main():
if len(sys.argv) != 1:
- print >>sys.stderr, 'usage: %s' % sys.argv[0]
+ print('usage: %s' % sys.argv[0], file=sys.stderr)
return 1
# Quietly exit if there's no SDK support for this platform.
@@ -135,7 +138,7 @@
subprocess.check_call([os.path.join(sdk_root, 'gen_build_defs.py')])
return 0
- print 'Downloading SDK %s...' % sdk_hash
+ print('Downloading SDK %s...' % sdk_hash)
if os.path.isdir(output_dir):
shutil.rmtree(output_dir)
diff --git a/build/gn_run_binary.py b/build/gn_run_binary.py
index d1685a3..d7e2926 100644
--- a/build/gn_run_binary.py
+++ b/build/gn_run_binary.py
@@ -8,6 +8,8 @@
python gn_run_binary.py <binary_name> [args ...]
"""
+from __future__ import print_function
+
import os
import subprocess
import sys
@@ -28,7 +30,7 @@
# Windows error codes such as 0xC0000005 and 0xC0000409 are much easier to
# recognize and differentiate in hex. In order to print them as unsigned
# hex we need to add 4 Gig to them.
- print '%s failed with exit code 0x%08X' % (sys.argv[1], ret + (1 << 32))
+ print('%s failed with exit code 0x%08X' % (sys.argv[1], ret + (1 << 32)))
else:
- print '%s failed with exit code %d' % (sys.argv[1], ret)
+ print('%s failed with exit code %d' % (sys.argv[1], ret))
sys.exit(ret)
diff --git a/build/install-build-deps.sh b/build/install-build-deps.sh
index 3b4045c..2314bcba 100755
--- a/build/install-build-deps.sh
+++ b/build/install-build-deps.sh
@@ -34,13 +34,14 @@
echo "Building apt package list." >&2
apt-cache dumpavail | \
python -c '\
+ from __future__ import print_function; \
import re,sys; \
o = sys.stdin.read(); \
p = {"i386": ":i386"}; \
f = re.M | re.S; \
r = re.compile(r"^Package: (.+?)$.+?^Architecture: (.+?)$", f); \
m = ["%s%s" % (x, p.get(y, "")) for x, y in re.findall(r, o)]; \
- print "\n".join(m)'
+ print("\n".join(m))'
}
# Checks whether a particular package is available in the repos.
diff --git a/build/linux/dump_app_syms.py b/build/linux/dump_app_syms.py
index 12e693e..f156baf3 100644
--- a/build/linux/dump_app_syms.py
+++ b/build/linux/dump_app_syms.py
@@ -5,13 +5,15 @@
# Helper script to run dump_syms on Chrome Linux executables and strip
# them if needed.
+from __future__ import print_function
+
import os
import subprocess
import sys
if len(sys.argv) != 5:
- print "dump_app_syms.py <dump_syms_exe> <strip_binary>"
- print " <binary_with_symbols> <symbols_output>"
+ print("dump_app_syms.py <dump_syms_exe> <strip_binary>")
+ print(" <binary_with_symbols> <symbols_output>")
sys.exit(1)
dumpsyms = sys.argv[1]
diff --git a/build/linux/install-chromeos-fonts.py b/build/linux/install-chromeos-fonts.py
index 54d0ede..affe132a 100755
--- a/build/linux/install-chromeos-fonts.py
+++ b/build/linux/install-chromeos-fonts.py
@@ -7,6 +7,8 @@
# This script can be run manually (as root), but is also run as part
# install-build-deps.sh.
+from __future__ import print_function
+
import os
import shutil
import subprocess
@@ -34,15 +36,15 @@
def main(args):
if not sys.platform.startswith('linux'):
- print "Error: %s must be run on Linux." % __file__
+ print("Error: %s must be run on Linux." % __file__)
return 1
if os.getuid() != 0:
- print "Error: %s must be run as root." % __file__
+ print("Error: %s must be run as root." % __file__)
return 1
if not os.path.isdir(FONTS_DIR):
- print "Error: Destination directory does not exist: %s" % FONTS_DIR
+ print("Error: Destination directory does not exist: %s" % FONTS_DIR)
return 1
dest_dir = os.path.join(FONTS_DIR, 'chromeos')
@@ -51,7 +53,7 @@
if os.path.exists(stamp):
with open(stamp) as s:
if s.read() == '\n'.join(URLS):
- print "Chrome OS fonts already up to date in %s." % dest_dir
+ print("Chrome OS fonts already up to date in %s." % dest_dir)
return 0
if os.path.isdir(dest_dir):
@@ -59,7 +61,7 @@
os.mkdir(dest_dir)
os.chmod(dest_dir, 0755)
- print "Installing Chrome OS fonts to %s." % dest_dir
+ print("Installing Chrome OS fonts to %s." % dest_dir)
for url in URLS:
tarball = os.path.join(dest_dir, os.path.basename(url))
subprocess.check_call(['curl', '-L', url, '-o', tarball])
@@ -82,7 +84,7 @@
for file in files:
os.chmod(os.path.join(base, file), 0644)
- print """\
+ print("""\
Chrome OS font rendering settings are specified using Fontconfig. If your
system's configuration doesn't match Chrome OS's (which vary for different
@@ -110,7 +112,7 @@
out), add the following immediately before the "</fontconfig>" line:
<include ignore_missing="yes">/path/to/src/third_party/chromiumos-overlay/media-libs/fontconfig/files/local.conf</include>
-"""
+""")
return 0
diff --git a/build/linux/rewrite_dirs.py b/build/linux/rewrite_dirs.py
index 30f22f0..17659c3 100755
--- a/build/linux/rewrite_dirs.py
+++ b/build/linux/rewrite_dirs.py
@@ -5,6 +5,8 @@
"""Rewrites paths in -I, -L and other option to be relative to a sysroot."""
+from __future__ import print_function
+
import sys
import os
import optparse
@@ -63,7 +65,7 @@
for line in sys.stdin.readlines():
line = RewriteLine(line.strip(), opts)
- print line
+ print(line)
return 0
diff --git a/build/linux/sysroot_scripts/build_and_upload.py b/build/linux/sysroot_scripts/build_and_upload.py
index 6a90fdc..007e078 100755
--- a/build/linux/sysroot_scripts/build_and_upload.py
+++ b/build/linux/sysroot_scripts/build_and_upload.py
@@ -7,6 +7,8 @@
UploadSysroot for each supported arch of each sysroot creator.
"""
+from __future__ import print_function
+
import glob
import hashlib
import json
@@ -87,13 +89,13 @@
for _, proc in procs:
proc.join()
- print "SYSROOT CREATION SUMMARY"
+ print("SYSROOT CREATION SUMMARY")
failures = 0
for name, proc in procs:
if proc.exitcode:
failures += 1
status = "FAILURE" if proc.exitcode else "SUCCESS"
- print "%s sysroot creation\t%s" % (name, status)
+ print("%s sysroot creation\t%s" % (name, status))
return failures
diff --git a/build/linux/sysroot_scripts/find_incompatible_glibc_symbols.py b/build/linux/sysroot_scripts/find_incompatible_glibc_symbols.py
index 426e17f..d79a89b 100755
--- a/build/linux/sysroot_scripts/find_incompatible_glibc_symbols.py
+++ b/build/linux/sysroot_scripts/find_incompatible_glibc_symbols.py
@@ -6,6 +6,8 @@
"""Find incompatible symbols in glibc and output a list of replacements.
"""
+from __future__ import print_function
+
import re
import sys
@@ -55,4 +57,4 @@
print('// Chromium-specific hack.')
print('// See explanation in sysroot-creator.sh.')
for replacement in replacements:
- print replacement
+ print(replacement)
diff --git a/build/linux/sysroot_scripts/install-sysroot.py b/build/linux/sysroot_scripts/install-sysroot.py
index 115dce4..858589ae 100755
--- a/build/linux/sysroot_scripts/install-sysroot.py
+++ b/build/linux/sysroot_scripts/install-sysroot.py
@@ -18,6 +18,8 @@
# time chrome's build dependencies are changed but should also be updated
# periodically to include upstream security fixes from Debian.
+from __future__ import print_function
+
import hashlib
import json
import platform
@@ -76,8 +78,8 @@
if options.print_hash:
arch = options.print_hash
- print GetSysrootDict(DEFAULT_TARGET_PLATFORM,
- ARCH_TRANSLATIONS.get(arch, arch))['Sha1Sum']
+ print(GetSysrootDict(DEFAULT_TARGET_PLATFORM,
+ ARCH_TRANSLATIONS.get(arch, arch))['Sha1Sum'])
return 0
if options.arch:
InstallSysroot(DEFAULT_TARGET_PLATFORM,
@@ -86,7 +88,7 @@
for arch in VALID_ARCHS:
InstallSysroot(DEFAULT_TARGET_PLATFORM, arch)
else:
- print 'You much specify one of the options.'
+ print('You much specify one of the options.')
return 1
return 0
@@ -122,13 +124,13 @@
if s.read() == url:
return
- print 'Installing Debian %s %s root image: %s' % \
- (target_platform, target_arch, sysroot)
+ print('Installing Debian %s %s root image: %s' % \
+ (target_platform, target_arch, sysroot))
if os.path.isdir(sysroot):
shutil.rmtree(sysroot)
os.mkdir(sysroot)
tarball = os.path.join(sysroot, tarball_filename)
- print 'Downloading %s' % url
+ print('Downloading %s' % url)
sys.stdout.flush()
sys.stderr.flush()
for _ in range(3):
diff --git a/build/linux/unbundle/remove_bundled_libraries.py b/build/linux/unbundle/remove_bundled_libraries.py
index 1cf2841b..a1cfffb3 100755
--- a/build/linux/unbundle/remove_bundled_libraries.py
+++ b/build/linux/unbundle/remove_bundled_libraries.py
@@ -9,6 +9,7 @@
See README for more details.
"""
+from __future__ import print_function
import optparse
import os.path
@@ -21,8 +22,8 @@
os.path.join(my_dirname, '..', '..', '..'))
if os.path.join(source_tree_root, 'build', 'linux', 'unbundle') != my_dirname:
- print ('Sanity check failed: please run this script from ' +
- 'build/linux/unbundle directory.')
+ print('Sanity check failed: please run this script from '
+ 'build/linux/unbundle directory.')
return 1
parser = optparse.OptionParser()
@@ -84,7 +85,7 @@
os.remove(path)
else:
# By default just print paths that would be removed.
- print path
+ print(path)
exit_code = 0
@@ -92,12 +93,12 @@
# up to date.
for exclusion, used in exclusion_used.iteritems():
if not used:
- print '%s does not exist' % exclusion
+ print('%s does not exist' % exclusion)
exit_code = 1
if not options.do_remove:
- print ('To actually remove files printed above, please pass ' +
- '--do-remove flag.')
+ print('To actually remove files printed above, please pass '
+ '--do-remove flag.')
return exit_code
diff --git a/build/locale_tool.py b/build/locale_tool.py
index 542a1e5..2c63915 100755
--- a/build/locale_tool.py
+++ b/build/locale_tool.py
@@ -27,6 +27,9 @@
inside its <outputs> section that breaks the script. The check will fail, and
trying to fix it too, but at least the file will not be modified.
"""
+
+from __future__ import print_function
+
import argparse
import json
import os
@@ -103,9 +106,9 @@
errors.append('Unexpected locales: %s' % extra_locales)
if errors:
- print 'Errors in %s definition:' % list_name
+ print('Errors in %s definition:' % list_name)
for error in errors:
- print ' %s\n' % error
+ print(' %s\n' % error)
return True
return False
@@ -202,22 +205,22 @@
Returns:
True at the moment.
"""
- print '%sProcessing %s...' % (_CONSOLE_START_LINE, input_file),
+ print('%sProcessing %s...' % (_CONSOLE_START_LINE, input_file), end=' ')
sys.stdout.flush()
with open(input_file) as f:
input_lines = f.readlines()
errors = check_func(input_file, input_lines, locales)
if errors:
- print '\n%s%s' % (_CONSOLE_START_LINE, '\n'.join(errors))
+ print('\n%s%s' % (_CONSOLE_START_LINE, '\n'.join(errors)))
if fix_func:
try:
input_lines = fix_func(input_file, input_lines, locales)
output = ''.join(input_lines)
with open(input_file, 'wt') as f:
f.write(output)
- print 'Fixed %s.' % input_file
+ print('Fixed %s.' % input_file)
except Exception as e: # pylint: disable=broad-except
- print 'Skipped %s: %s' % (input_file, e)
+ print('Skipped %s: %s' % (input_file, e))
return True
@@ -1308,9 +1311,9 @@
def Run(self):
locale_list = self.TYPE_MAP[self.args.type]()
if self.args.as_json:
- print '[%s]' % ", ".join("'%s'" % loc for loc in locale_list)
+ print('[%s]' % ", ".join("'%s'" % loc for loc in locale_list))
else:
- print ' '.join(locale_list)
+ print(' '.join(locale_list))
class _CheckInputFileBaseCommand(_Command):
@@ -1368,7 +1371,7 @@
locales,
self.check_func.__func__,
self.fix_func.__func__ if args.fix_inplace else None)
- print '%sDone.' % (_CONSOLE_START_LINE)
+ print('%sDone.' % (_CONSOLE_START_LINE))
class _CheckGrdAndroidOutputsCommand(_CheckInputFileBaseCommand):
diff --git a/build/mac/find_sdk.py b/build/mac/find_sdk.py
index 540a3202..cb77c77 100755
--- a/build/mac/find_sdk.py
+++ b/build/mac/find_sdk.py
@@ -11,6 +11,8 @@
python find_sdk.py [--developer_dir DEVELOPER_DIR] 10.6 # Ignores SDKs < 10.6
"""
+from __future__ import print_function
+
import os
import re
import subprocess
@@ -56,8 +58,8 @@
stderr=subprocess.STDOUT)
out, err = job.communicate()
if job.returncode != 0:
- print >> sys.stderr, out
- print >> sys.stderr, err
+ print(out, file=sys.stderr)
+ print(err, file=sys.stderr)
raise Exception('Error %d running xcode-select' % job.returncode)
sdk_dir = os.path.join(
out.rstrip(), 'Platforms/MacOSX.platform/Developer/SDKs')
@@ -78,22 +80,22 @@
best_sdk = sorted(sdks, key=parse_version)[0]
if options.verify and best_sdk != min_sdk_version and not options.sdk_path:
- print >> sys.stderr, ''
- print >> sys.stderr, ' vvvvvvv'
- print >> sys.stderr, ''
- print >> sys.stderr, \
- 'This build requires the %s SDK, but it was not found on your system.' \
- % min_sdk_version
- print >> sys.stderr, \
- 'Either install it, or explicitly set mac_sdk in your GYP_DEFINES.'
- print >> sys.stderr, ''
- print >> sys.stderr, ' ^^^^^^^'
- print >> sys.stderr, ''
+ print('', file=sys.stderr)
+ print(' vvvvvvv', file=sys.stderr)
+ print('', file=sys.stderr)
+ print('This build requires the %s SDK, but it was not found on your system.' \
+ % min_sdk_version, file=sys.stderr)
+ print(
+ 'Either install it, or explicitly set mac_sdk in your GYP_DEFINES.',
+ file=sys.stderr)
+ print('', file=sys.stderr)
+ print(' ^^^^^^^', file=sys.stderr)
+ print('', file=sys.stderr)
sys.exit(1)
if options.print_sdk_path:
- print subprocess.check_output(
- ['xcrun', '-sdk', 'macosx' + best_sdk, '--show-sdk-path']).strip()
+ print(subprocess.check_output(
+ ['xcrun', '-sdk', 'macosx' + best_sdk, '--show-sdk-path']).strip())
return best_sdk
@@ -101,5 +103,5 @@
if __name__ == '__main__':
if sys.platform != 'darwin':
raise Exception("This script only runs on Mac")
- print main()
+ print(main())
sys.exit(0)
diff --git a/build/mac/should_use_hermetic_xcode.py b/build/mac/should_use_hermetic_xcode.py
index 08e9886..450c4038 100755
--- a/build/mac/should_use_hermetic_xcode.py
+++ b/build/mac/should_use_hermetic_xcode.py
@@ -14,6 +14,8 @@
python should_use_hermetic_xcode.py <target_os>
"""
+from __future__ import print_function
+
import os
import sys
@@ -42,5 +44,5 @@
if __name__ == '__main__':
- print main()
+ print(main())
sys.exit(0)
diff --git a/build/mac/tweak_info_plist.py b/build/mac/tweak_info_plist.py
index 9ea794b..bbf3332d 100755
--- a/build/mac/tweak_info_plist.py
+++ b/build/mac/tweak_info_plist.py
@@ -20,6 +20,8 @@
# by the time the app target is done, the info.plist is correct.
#
+from __future__ import print_function
+
import optparse
import os
import plistlib
@@ -123,7 +125,7 @@
# True if the string is composed only of digits (and thus match \d+ regexp).
groups = version.split('.')
if len(groups) != 4 or not all(element.isdigit() for element in groups):
- print >>sys.stderr, 'Invalid version string specified: "%s"' % version
+ print('Invalid version string specified: "%s"' % version, file=sys.stderr)
return False
values = dict(zip(('MAJOR', 'MINOR', 'BUILD', 'PATCH'), groups))
@@ -153,7 +155,7 @@
if scm_revision != None:
plist['SCMRevision'] = scm_revision
elif add_keys:
- print >>sys.stderr, 'Could not determine SCM revision. This may be OK.'
+ print('Could not determine SCM revision. This may be OK.', file=sys.stderr)
return True
@@ -265,11 +267,11 @@
(options, args) = parser.parse_args(argv)
if len(args) > 0:
- print >>sys.stderr, parser.get_usage()
+ print(parser.get_usage(), file=sys.stderr)
return 1
if not options.plist_path:
- print >>sys.stderr, 'No --plist specified.'
+ print('No --plist specified.', file=sys.stderr)
return 1
# Read the plist into its parsed format. Convert the file to 'xml1' as
@@ -285,12 +287,12 @@
if options.version_overrides:
for pair in options.version_overrides:
if not '=' in pair:
- print >>sys.stderr, 'Invalid value for --version-overrides:', pair
+ print('Invalid value for --version-overrides:', pair, file=sys.stderr)
return 1
key, value = pair.split('=', 1)
overrides[key] = value
if key not in ('MAJOR', 'MINOR', 'BUILD', 'PATCH'):
- print >>sys.stderr, 'Unsupported key for --version-overrides:', key
+ print('Unsupported key for --version-overrides:', key, file=sys.stderr)
return 1
if options.platform == 'mac':
@@ -326,7 +328,7 @@
# Add Breakpad if configured to do so.
if options.use_breakpad:
if options.branding is None:
- print >>sys.stderr, 'Use of Breakpad requires branding.'
+ print('Use of Breakpad requires branding.', file=sys.stderr)
return 1
# Map "target_os" passed from gn via the --platform parameter
# to the platform as known by breakpad.
@@ -339,7 +341,7 @@
# Add Keystone if configured to do so.
if options.use_keystone:
if options.bundle_identifier is None:
- print >>sys.stderr, 'Use of Keystone requires the bundle id.'
+ print('Use of Keystone requires the bundle id.', file=sys.stderr)
return 1
_AddKeystoneKeys(plist, options.bundle_identifier)
else:
diff --git a/build/mac_toolchain.py b/build/mac_toolchain.py
index 87ed2568..ea264a2f 100755
--- a/build/mac_toolchain.py
+++ b/build/mac_toolchain.py
@@ -16,6 +16,8 @@
the full revision, e.g. 9A235.
"""
+from __future__ import print_function
+
import os
import platform
import shutil
@@ -61,22 +63,22 @@
def RequestCipdAuthentication():
"""Requests that the user authenticate to access Xcode CIPD packages."""
- print 'Access to Xcode CIPD package requires authentication.'
- print '-----------------------------------------------------------------'
- print
- print 'You appear to be a Googler.'
- print
- print 'I\'m sorry for the hassle, but you may need to do a one-time manual'
- print 'authentication. Please run:'
- print
- print ' cipd auth-login'
- print
- print 'and follow the instructions.'
- print
- print 'NOTE: Use your google.com credentials, not chromium.org.'
- print
- print '-----------------------------------------------------------------'
- print
+ print('Access to Xcode CIPD package requires authentication.')
+ print('-----------------------------------------------------------------')
+ print()
+ print('You appear to be a Googler.')
+ print()
+ print('I\'m sorry for the hassle, but you may need to do a one-time manual')
+ print('authentication. Please run:')
+ print()
+ print(' cipd auth-login')
+ print()
+ print('and follow the instructions.')
+ print()
+ print('NOTE: Use your google.com credentials, not chromium.org.')
+ print()
+ print('-----------------------------------------------------------------')
+ print()
sys.stdout.flush()
@@ -132,11 +134,11 @@
return 0
if not _UseHermeticToolchain():
- print 'Skipping Mac toolchain installation for mac'
+ print('Skipping Mac toolchain installation for mac')
return 0
if not PlatformMeetsHermeticXcodeRequirements():
- print 'OS version does not support toolchain.'
+ print('OS version does not support toolchain.')
return 0
toolchain_version = os.environ.get('MAC_TOOLCHAIN_REVISION',
@@ -156,8 +158,8 @@
# TODO(crbug.com/797051): remove this once the old "hermetic" solution is no
# longer in use.
if os.path.exists(stamp_file):
- print 'Detected old hermetic installation at %s. Deleting.' % (
- toolchain_root)
+ print(
+ 'Detected old hermetic installation at %s. Deleting.' % toolchain_root)
shutil.rmtree(toolchain_root)
success = InstallXcode(toolchain_version, installer_cmd, xcode_app_path)
diff --git a/build/package_mac_toolchain.py b/build/package_mac_toolchain.py
index 48672bb..2c03ef37 100755
--- a/build/package_mac_toolchain.py
+++ b/build/package_mac_toolchain.py
@@ -8,6 +8,8 @@
Stored in in https://pantheon.corp.google.com/storage/browser/chrome-mac-sdk/.
"""
+from __future__ import print_function
+
import argparse
import glob
import os
@@ -92,7 +94,7 @@
try:
info = plistlib.readPlist(plist_file)
except:
- print "Invalid Xcode dir."
+ print("Invalid Xcode dir.")
return 0
build_version = info['ProductBuildVersion']
@@ -113,14 +115,14 @@
% (build_version, next_count - 1))
if raw_input().lower() not in set(['yes','y', 'ye']):
- print "Skipping duplicate upload."
+ print("Skipping duplicate upload.")
return 0
os.chdir(parser_args.target_dir)
toolchain_file_name = "%s-%s-%s" % (fname, build_version, next_count)
toolchain_name = tempfile.mktemp(suffix='toolchain.tgz')
- print "Creating %s (%s)." % (toolchain_file_name, toolchain_name)
+ print("Creating %s (%s)." % (toolchain_file_name, toolchain_name))
os.environ["COPYFILE_DISABLE"] = "1"
os.environ["GZ_OPT"] = "-8"
args = ['tar', '-cvzf', toolchain_name]
@@ -133,12 +135,12 @@
args.extend(['.'])
subprocess.check_call(args)
- print "Uploading %s toolchain." % toolchain_file_name
+ print("Uploading %s toolchain." % toolchain_file_name)
destination_path = '%s/%s.tgz' % (TOOLCHAIN_URL, toolchain_file_name)
subprocess.check_call(['gsutil.py', 'cp', '-n', toolchain_name,
destination_path])
- print "Done with %s upload." % toolchain_file_name
+ print("Done with %s upload." % toolchain_file_name)
return 0
if __name__ == '__main__':
diff --git a/build/protoc_java.py b/build/protoc_java.py
index 09cd808..4eb8eae 100755
--- a/build/protoc_java.py
+++ b/build/protoc_java.py
@@ -15,6 +15,8 @@
4. Creates a new stamp file.
"""
+from __future__ import print_function
+
import os
import optparse
import shutil
@@ -41,11 +43,11 @@
build_utils.CheckOptions(options, parser, ['protoc', 'proto_path'])
if not options.java_out_dir and not options.srcjar:
- print 'One of --java-out-dir or --srcjar must be specified.'
+ print('One of --java-out-dir or --srcjar must be specified.')
return 1
if not options.nano and not options.protoc_javalite_plugin_dir:
- print 'One of --nano or --protoc-javalite-plugin-dir must be specified.'
+ print('One of --nano or --protoc-javalite-plugin-dir must be specified.')
return 1
with build_utils.TempDir() as temp_dir:
diff --git a/build/redirect_stdout.py b/build/redirect_stdout.py
index 72d0732..166293c 100644
--- a/build/redirect_stdout.py
+++ b/build/redirect_stdout.py
@@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import subprocess
import sys
@@ -12,7 +14,7 @@
if __name__ == '__main__':
if len(sys.argv) < 2:
- print >> sys.stderr, "Usage: %s output_file command..." % (sys.argv[0])
+ print("Usage: %s output_file command..." % sys.argv[0], file=sys.stderr)
sys.exit(1)
with open(sys.argv[1], 'w') as fp:
diff --git a/build/rm.py b/build/rm.py
index 5ca642d..43a663d6 100755
--- a/build/rm.py
+++ b/build/rm.py
@@ -8,6 +8,8 @@
This module works much like the rm posix command.
"""
+from __future__ import print_function
+
import argparse
import os
import sys
@@ -25,7 +27,7 @@
os.remove(f)
except OSError:
if not args.force:
- print >>sys.stderr, "'%s' does not exist" % f
+ print("'%s' does not exist" % f, file=sys.stderr)
return 1
with open(args.stamp, 'w'):
diff --git a/build/run_swarming_xcode_install.py b/build/run_swarming_xcode_install.py
index a731c1b..1ed09263 100755
--- a/build/run_swarming_xcode_install.py
+++ b/build/run_swarming_xcode_install.py
@@ -15,6 +15,8 @@
--isolate-server touch-isolate.appspot.com
"""
+from __future__ import print_function
+
import argparse
import os
import shutil
@@ -39,7 +41,7 @@
script_dir = os.path.dirname(os.path.abspath(__file__))
tmp_dir = tempfile.mkdtemp(prefix='swarming_xcode')
try:
- print 'Making isolate.'
+ print('Making isolate.')
shutil.copyfile(os.path.join(script_dir, 'swarming_xcode_install.py'),
os.path.join(tmp_dir, 'swarming_xcode_install.py'))
shutil.copyfile(os.path.join(script_dir, 'mac_toolchain.py'),
@@ -52,7 +54,7 @@
]
isolate_hash = subprocess.check_output(cmd).split()[0]
- print 'Running swarming_xcode_install.'
+ print('Running swarming_xcode_install.')
# TODO(crbug.com/765361): The dimensions below should be updated once
# swarming for iOS is fleshed out, likely removing xcode_version 9 and
# adding different dimensions.
@@ -70,7 +72,7 @@
'python', 'swarming_xcode_install.py',
]
subprocess.check_call(cmd)
- print 'All tasks completed.'
+ print('All tasks completed.')
finally:
shutil.rmtree(tmp_dir)
diff --git a/build/swarming_xcode_install.py b/build/swarming_xcode_install.py
index 7764aa55..d214d0b0 100755
--- a/build/swarming_xcode_install.py
+++ b/build/swarming_xcode_install.py
@@ -7,6 +7,8 @@
Script used to install Xcode on the swarming bots.
"""
+from __future__ import print_function
+
import os
import shutil
import subprocess
@@ -30,12 +32,12 @@
found_version = \
subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE).communicate()[0]
if VERSION in found_version:
- print "Xcode %s already installed" % VERSION
+ print("Xcode %s already installed" % VERSION)
sys.exit(0)
# Confirm old dir is there first.
if not os.path.exists(REMOVE_DIR):
- print "Failing early since %s isn't there." % REMOVE_DIR
+ print("Failing early since %s isn't there." % REMOVE_DIR)
sys.exit(1)
# Download Xcode.
@@ -61,4 +63,3 @@
if __name__ == '__main__':
sys.exit(main())
-
diff --git a/build/toolchain/clang_code_coverage_wrapper.py b/build/toolchain/clang_code_coverage_wrapper.py
index 96978056..679a3b5 100755
--- a/build/toolchain/clang_code_coverage_wrapper.py
+++ b/build/toolchain/clang_code_coverage_wrapper.py
@@ -39,6 +39,8 @@
--files-to-instrument=coverage_instrumentation_input.txt
"""
+from __future__ import print_function
+
import argparse
import os
import subprocess
@@ -124,7 +126,7 @@
# obj/base/base/file_path.o
index_dash_c = compile_command.index('-c')
except ValueError:
- print '-c argument is not found in the compile command.'
+ print('-c argument is not found in the compile command.')
raise
if index_dash_c + 1 >= len(compile_command):
diff --git a/build/toolchain/mac/filter_libtool.py b/build/toolchain/mac/filter_libtool.py
index 3b16151..b458f06 100644
--- a/build/toolchain/mac/filter_libtool.py
+++ b/build/toolchain/mac/filter_libtool.py
@@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import os
import re
import subprocess
@@ -39,7 +41,7 @@
_, err = libtoolout.communicate()
for line in err.splitlines():
if not IsBlacklistedLine(line):
- print >>sys.stderr, line
+ print(line, file=sys.stderr)
# Unconditionally touch the output .a file on the command line if present
# and the command succeeded. A bit hacky.
if not libtoolout.returncode:
diff --git a/build/toolchain/mac/get_tool_mtime.py b/build/toolchain/mac/get_tool_mtime.py
index 4106344b..ff0254c 100644
--- a/build/toolchain/mac/get_tool_mtime.py
+++ b/build/toolchain/mac/get_tool_mtime.py
@@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import os
import sys
@@ -14,4 +16,4 @@
if __name__ == '__main__':
for f in sys.argv[1:]:
variable = os.path.splitext(os.path.basename(f))[0]
- print '%s = %d' % (variable, os.path.getmtime(f))
+ print('%s = %d' % (variable, os.path.getmtime(f)))
diff --git a/build/toolchain/win/midl.py b/build/toolchain/win/midl.py
index 09fec0b8c..618252a 100644
--- a/build/toolchain/win/midl.py
+++ b/build/toolchain/win/midl.py
@@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import array
import difflib
import distutils.dir_util
@@ -205,7 +207,7 @@
for x in lines if x.startswith(prefixes))
for line in lines:
if not line.startswith(prefixes) and line not in processing:
- print line
+ print(line)
if popen.returncode != 0:
return popen.returncode
@@ -215,18 +217,19 @@
# Now compare the output in tmp_dir to the copied-over outputs.
diff = filecmp.dircmp(tmp_dir, outdir)
if diff.diff_files:
- print 'midl.exe output different from files in %s, see %s' \
- % (outdir, tmp_dir)
+ print('midl.exe output different from files in %s, see %s' % (outdir,
+ tmp_dir))
for f in diff.diff_files:
if f.endswith('.tlb'): continue
fromfile = os.path.join(outdir, f)
tofile = os.path.join(tmp_dir, f)
- print ''.join(difflib.unified_diff(open(fromfile, 'U').readlines(),
- open(tofile, 'U').readlines(),
- fromfile, tofile))
+ print(''.join(
+ difflib.unified_diff(
+ open(fromfile, 'U').readlines(),
+ open(tofile, 'U').readlines(), fromfile, tofile)))
delete_tmp_dir = False
- print 'To rebaseline:'
- print ' copy /y %s\* %s' % (tmp_dir, source)
+ print('To rebaseline:')
+ print(' copy /y %s\* %s' % (tmp_dir, source))
sys.exit(1)
return 0
finally:
diff --git a/build/util/lib/common/perf_tests_results_helper.py b/build/util/lib/common/perf_tests_results_helper.py
index 59bb5e43..153886d 100644
--- a/build/util/lib/common/perf_tests_results_helper.py
+++ b/build/util/lib/common/perf_tests_results_helper.py
@@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+from __future__ import print_function
+
import re
import sys
@@ -90,7 +92,7 @@
def PrintPages(page_list):
"""Prints list of pages to stdout in the format required by perf tests."""
- print 'Pages: [%s]' % ','.join([_EscapePerfResult(p) for p in page_list])
+ print('Pages: [%s]' % ','.join([_EscapePerfResult(p) for p in page_list]))
def PrintPerfResult(measurement, trace, values, units,
@@ -161,7 +163,7 @@
if sd:
output += '\nSd %s: %f%s' % (measurement, sd, units)
if print_to_stdout:
- print output
+ print(output)
sys.stdout.flush()
return output
diff --git a/build/win/gn_meta_sln.py b/build/win/gn_meta_sln.py
index 9f72eda..f97f47b 100644
--- a/build/win/gn_meta_sln.py
+++ b/build/win/gn_meta_sln.py
@@ -6,6 +6,8 @@
# Helper utility to combine GN-generated Visual Studio projects into
# a single meta-solution.
+from __future__ import print_function
+
import os
import glob
import re