Commit 1aa2c343 authored by Jie Luo's avatar Jie Luo Committed by GitHub

Merge pull request #3516 from cclauss/patch-3

Python 3 compatibility fixes: print(), long(), etc.
parents 5ab8ae75 dded80f9
...@@ -35,7 +35,6 @@ This is sort of like comm(1), except it recognizes comments and ignores them. ...@@ -35,7 +35,6 @@ This is sort of like comm(1), except it recognizes comments and ignores them.
""" """
import argparse import argparse
import fileinput
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description='Adds/removes failures from the failure list.') description='Adds/removes failures from the failure list.')
...@@ -62,7 +61,8 @@ for remove_file in (args.remove_list or []): ...@@ -62,7 +61,8 @@ for remove_file in (args.remove_list or []):
add_list = sorted(add_set, reverse=True) add_list = sorted(add_set, reverse=True)
existing_list = file(args.filename).read() with open(args.filename) as in_file:
existing_list = in_file.read()
with open(args.filename, "w") as f: with open(args.filename, "w") as f:
for line in existing_list.splitlines(True): for line in existing_list.splitlines(True):
......
...@@ -5,6 +5,12 @@ ...@@ -5,6 +5,12 @@
import addressbook_pb2 import addressbook_pb2
import sys import sys
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
# This function fills in a Person message based on user input. # This function fills in a Person message based on user input.
def PromptForAddress(person): def PromptForAddress(person):
person.id = int(raw_input("Enter person ID number: ")) person.id = int(raw_input("Enter person ID number: "))
...@@ -30,13 +36,14 @@ def PromptForAddress(person): ...@@ -30,13 +36,14 @@ def PromptForAddress(person):
elif type == "work": elif type == "work":
phone_number.type = addressbook_pb2.Person.WORK phone_number.type = addressbook_pb2.Person.WORK
else: else:
print "Unknown phone type; leaving as default value." print("Unknown phone type; leaving as default value.")
# Main procedure: Reads the entire address book from a file, # Main procedure: Reads the entire address book from a file,
# adds one person based on user input, then writes it back out to the same # adds one person based on user input, then writes it back out to the same
# file. # file.
if len(sys.argv) != 2: if len(sys.argv) != 2:
print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE" print("Usage:", sys.argv[0], "ADDRESS_BOOK_FILE")
sys.exit(-1) sys.exit(-1)
address_book = addressbook_pb2.AddressBook() address_book = addressbook_pb2.AddressBook()
...@@ -46,7 +53,7 @@ try: ...@@ -46,7 +53,7 @@ try:
with open(sys.argv[1], "rb") as f: with open(sys.argv[1], "rb") as f:
address_book.ParseFromString(f.read()) address_book.ParseFromString(f.read())
except IOError: except IOError:
print sys.argv[1] + ": File not found. Creating a new file." print(sys.argv[1] + ": File not found. Creating a new file.")
# Add an address. # Add an address.
PromptForAddress(address_book.people.add()) PromptForAddress(address_book.people.add())
......
...@@ -2,30 +2,33 @@ ...@@ -2,30 +2,33 @@
# See README.txt for information and build instructions. # See README.txt for information and build instructions.
from __future__ import print_function
import addressbook_pb2 import addressbook_pb2
import sys import sys
# Iterates though all people in the AddressBook and prints info about them. # Iterates though all people in the AddressBook and prints info about them.
def ListPeople(address_book): def ListPeople(address_book):
for person in address_book.people: for person in address_book.people:
print "Person ID:", person.id print("Person ID:", person.id)
print " Name:", person.name print(" Name:", person.name)
if person.email != "": if person.email != "":
print " E-mail address:", person.email print(" E-mail address:", person.email)
for phone_number in person.phones: for phone_number in person.phones:
if phone_number.type == addressbook_pb2.Person.MOBILE: if phone_number.type == addressbook_pb2.Person.MOBILE:
print " Mobile phone #:", print(" Mobile phone #:", end=" ")
elif phone_number.type == addressbook_pb2.Person.HOME: elif phone_number.type == addressbook_pb2.Person.HOME:
print " Home phone #:", print(" Home phone #:", end=" ")
elif phone_number.type == addressbook_pb2.Person.WORK: elif phone_number.type == addressbook_pb2.Person.WORK:
print " Work phone #:", print(" Work phone #:", end=" ")
print phone_number.number print(phone_number.number)
# Main procedure: Reads the entire address book from a file and prints all # Main procedure: Reads the entire address book from a file and prints all
# the information inside. # the information inside.
if len(sys.argv) != 2: if len(sys.argv) != 2:
print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE" print("Usage:", sys.argv[0], "ADDRESS_BOOK_FILE")
sys.exit(-1) sys.exit(-1)
address_book = addressbook_pb2.AddressBook() address_book = addressbook_pb2.AddressBook()
......
...@@ -17,11 +17,12 @@ detailed test results. It runs as the last step before the Jenkins build ...@@ -17,11 +17,12 @@ detailed test results. It runs as the last step before the Jenkins build
finishes. finishes.
""" """
import os; import os
import sys; import sys
from yattag import Doc from yattag import Doc
from collections import defaultdict from collections import defaultdict
def readtests(basedir): def readtests(basedir):
tests = defaultdict(dict) tests = defaultdict(dict)
...@@ -68,6 +69,7 @@ def readtests(basedir): ...@@ -68,6 +69,7 @@ def readtests(basedir):
return ret return ret
def genxml(tests): def genxml(tests):
doc, tag, text = Doc().tagtext() doc, tag, text = Doc().tagtext()
...@@ -86,6 +88,7 @@ def genxml(tests): ...@@ -86,6 +88,7 @@ def genxml(tests):
return doc.getvalue() return doc.getvalue()
sys.stderr.write("make_test_output.py: writing XML from directory: " + sys.stderr.write("make_test_output.py: writing XML from directory: " +
sys.argv[1] + "\n"); sys.argv[1] + "\n")
print genxml(readtests(sys.argv[1])) print(genxml(readtests(sys.argv[1])))
...@@ -124,6 +124,7 @@ def _MacroRefRe(macro_names): ...@@ -124,6 +124,7 @@ def _MacroRefRe(macro_names):
return re.compile(r'\b(?P<macro_ref>(?P<name>(%s))\((?P<args>.*?)\))' % return re.compile(r'\b(?P<macro_ref>(?P<name>(%s))\((?P<args>.*?)\))' %
'|'.join(macro_names)) '|'.join(macro_names))
def _MacroArgRefRe(macro_arg_names): def _MacroArgRefRe(macro_arg_names):
# Takes in a list of macro arg names and makes a regex that will match # Takes in a list of macro arg names and makes a regex that will match
# uses of those args. # uses of those args.
...@@ -318,6 +319,7 @@ class MacroCollection(object): ...@@ -318,6 +319,7 @@ class MacroCollection(object):
return macro.body return macro.body
assert len(arg_values) == len(macro.args) assert len(arg_values) == len(macro.args)
args = dict(zip(macro.args, arg_values)) args = dict(zip(macro.args, arg_values))
def _lookupArg(match): def _lookupArg(match):
val = args[match.group('name')] val = args[match.group('name')]
opt = match.group('option') opt = match.group('option')
...@@ -350,6 +352,7 @@ class MacroCollection(object): ...@@ -350,6 +352,7 @@ class MacroCollection(object):
def _EvalMacrosRefs(self, text, macro_stack): def _EvalMacrosRefs(self, text, macro_stack):
macro_ref_re = _MacroRefRe(self._macros.keys()) macro_ref_re = _MacroRefRe(self._macros.keys())
def _resolveMacro(match): def _resolveMacro(match):
return self._Expand(match, macro_stack) return self._Expand(match, macro_stack)
return macro_ref_re.sub(_resolveMacro, text) return macro_ref_re.sub(_resolveMacro, text)
...@@ -498,7 +501,8 @@ class SourceFile(object): ...@@ -498,7 +501,8 @@ class SourceFile(object):
result.append('//%%PDDM-EXPAND-END %s' % result.append('//%%PDDM-EXPAND-END %s' %
captured_lines[0][directive_len:].strip()) captured_lines[0][directive_len:].strip())
else: else:
result.append('//%%PDDM-EXPAND-END (%s expansions)' % len(captured_lines)) result.append('//%%PDDM-EXPAND-END (%s expansions)' %
len(captured_lines))
return result return result
...@@ -669,15 +673,15 @@ def main(args): ...@@ -669,15 +673,15 @@ def main(args):
if src_file.processed_content != src_file.original_content: if src_file.processed_content != src_file.original_content:
if not opts.dry_run: if not opts.dry_run:
print 'Updating for "%s".' % a_path print('Updating for "%s".' % a_path)
with open(a_path, 'w') as f: with open(a_path, 'w') as f:
f.write(src_file.processed_content) f.write(src_file.processed_content)
else: else:
# Special result to indicate things need updating. # Special result to indicate things need updating.
print 'Update needed for "%s".' % a_path print('Update needed for "%s".' % a_path)
result = 1 result = 1
elif opts.verbose: elif opts.verbose:
print 'No update for "%s".' % a_path print('No update for "%s".' % a_path)
return result return result
......
...@@ -39,11 +39,15 @@ __author__ = 'robinson@google.com (Will Robinson)' ...@@ -39,11 +39,15 @@ __author__ = 'robinson@google.com (Will Robinson)'
import numbers import numbers
import operator import operator
import os.path import os.path
import sys
from google.protobuf import unittest_import_pb2 from google.protobuf import unittest_import_pb2
from google.protobuf import unittest_pb2 from google.protobuf import unittest_pb2
from google.protobuf import descriptor_pb2
try:
long # Python 2
except NameError:
long = int # Python 3
# Tests whether the given TestAllTypes message is proto2 or not. # Tests whether the given TestAllTypes message is proto2 or not.
# This is used to gate several fields/features that only exist # This is used to gate several fields/features that only exist
...@@ -51,6 +55,7 @@ from google.protobuf import descriptor_pb2 ...@@ -51,6 +55,7 @@ from google.protobuf import descriptor_pb2
def IsProto2(message): def IsProto2(message):
return message.DESCRIPTOR.syntax == "proto2" return message.DESCRIPTOR.syntax == "proto2"
def SetAllNonLazyFields(message): def SetAllNonLazyFields(message):
"""Sets every non-lazy field in the message to a unique value. """Sets every non-lazy field in the message to a unique value.
...@@ -707,8 +712,8 @@ class NonStandardInteger(numbers.Integral): ...@@ -707,8 +712,8 @@ class NonStandardInteger(numbers.Integral):
NonStandardInteger is the minimal legal specification for a custom Integral. NonStandardInteger is the minimal legal specification for a custom Integral.
As such, it does not support 0 < x < 5 and it is not hashable. As such, it does not support 0 < x < 5 and it is not hashable.
Note: This is added here instead of relying on numpy or a similar library with Note: This is added here instead of relying on numpy or a similar library
custom integers to limit dependencies. with custom integers to limit dependencies.
""" """
def __init__(self, val, error_string_on_conversion=None): def __init__(self, val, error_string_on_conversion=None):
...@@ -845,4 +850,3 @@ class NonStandardInteger(numbers.Integral): ...@@ -845,4 +850,3 @@ class NonStandardInteger(numbers.Integral):
def __repr__(self): def __repr__(self):
return 'NonStandardInteger(%s)' % self.val return 'NonStandardInteger(%s)' % self.val
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment