Merge pull request #3516 from cclauss/patch-3

Python 3 compatibility fixes: print(), long(), etc.
pull/3524/head
Jie Luo 7 years ago committed by GitHub
commit 1aa2c34387
  1. 4
      conformance/update_failure_list.py
  2. 13
      examples/add_person.py
  3. 19
      examples/list_people.py
  4. 11
      jenkins/make_test_output.py
  5. 24
      objectivec/DevTools/pddm.py
  6. 14
      python/google/protobuf/internal/test_util.py

@ -35,7 +35,6 @@ This is sort of like comm(1), except it recognizes comments and ignores them.
"""
import argparse
import fileinput
parser = argparse.ArgumentParser(
description='Adds/removes failures from the failure list.')
@ -62,7 +61,8 @@ for remove_file in (args.remove_list or []):
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:
for line in existing_list.splitlines(True):

@ -5,6 +5,12 @@
import addressbook_pb2
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.
def PromptForAddress(person):
person.id = int(raw_input("Enter person ID number: "))
@ -30,13 +36,14 @@ def PromptForAddress(person):
elif type == "work":
phone_number.type = addressbook_pb2.Person.WORK
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,
# adds one person based on user input, then writes it back out to the same
# file.
if len(sys.argv) != 2:
print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
print("Usage:", sys.argv[0], "ADDRESS_BOOK_FILE")
sys.exit(-1)
address_book = addressbook_pb2.AddressBook()
@ -46,7 +53,7 @@ try:
with open(sys.argv[1], "rb") as f:
address_book.ParseFromString(f.read())
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.
PromptForAddress(address_book.people.add())

@ -2,30 +2,33 @@
# See README.txt for information and build instructions.
from __future__ import print_function
import addressbook_pb2
import sys
# Iterates though all people in the AddressBook and prints info about them.
def ListPeople(address_book):
for person in address_book.people:
print "Person ID:", person.id
print " Name:", person.name
print("Person ID:", person.id)
print(" Name:", person.name)
if person.email != "":
print " E-mail address:", person.email
print(" E-mail address:", person.email)
for phone_number in person.phones:
if phone_number.type == addressbook_pb2.Person.MOBILE:
print " Mobile phone #:",
print(" Mobile phone #:", end=" ")
elif phone_number.type == addressbook_pb2.Person.HOME:
print " Home phone #:",
print(" Home phone #:", end=" ")
elif phone_number.type == addressbook_pb2.Person.WORK:
print " Work phone #:",
print phone_number.number
print(" Work phone #:", end=" ")
print(phone_number.number)
# Main procedure: Reads the entire address book from a file and prints all
# the information inside.
if len(sys.argv) != 2:
print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
print("Usage:", sys.argv[0], "ADDRESS_BOOK_FILE")
sys.exit(-1)
address_book = addressbook_pb2.AddressBook()

@ -17,11 +17,12 @@ detailed test results. It runs as the last step before the Jenkins build
finishes.
"""
import os;
import sys;
import os
import sys
from yattag import Doc
from collections import defaultdict
def readtests(basedir):
tests = defaultdict(dict)
@ -68,6 +69,7 @@ def readtests(basedir):
return ret
def genxml(tests):
doc, tag, text = Doc().tagtext()
@ -86,6 +88,7 @@ def genxml(tests):
return doc.getvalue()
sys.stderr.write("make_test_output.py: writing XML from directory: " +
sys.argv[1] + "\n");
print genxml(readtests(sys.argv[1]))
sys.argv[1] + "\n")
print(genxml(readtests(sys.argv[1])))

@ -124,6 +124,7 @@ def _MacroRefRe(macro_names):
return re.compile(r'\b(?P<macro_ref>(?P<name>(%s))\((?P<args>.*?)\))' %
'|'.join(macro_names))
def _MacroArgRefRe(macro_arg_names):
# Takes in a list of macro arg names and makes a regex that will match
# uses of those args.
@ -318,25 +319,26 @@ class MacroCollection(object):
return macro.body
assert len(arg_values) == len(macro.args)
args = dict(zip(macro.args, arg_values))
def _lookupArg(match):
val = args[match.group('name')]
opt = match.group('option')
if opt:
if opt == 'S': # Spaces for the length
if opt == 'S': # Spaces for the length
return ' ' * len(val)
elif opt == 'l': # Lowercase first character
elif opt == 'l': # Lowercase first character
if val:
return val[0].lower() + val[1:]
else:
return val
elif opt == 'L': # All Lowercase
elif opt == 'L': # All Lowercase
return val.lower()
elif opt == 'u': # Uppercase first character
elif opt == 'u': # Uppercase first character
if val:
return val[0].upper() + val[1:]
else:
return val
elif opt == 'U': # All Uppercase
elif opt == 'U': # All Uppercase
return val.upper()
else:
raise PDDMError('Unknown arg option "%s$%s" while expanding "%s".%s'
@ -350,6 +352,7 @@ class MacroCollection(object):
def _EvalMacrosRefs(self, text, macro_stack):
macro_ref_re = _MacroRefRe(self._macros.keys())
def _resolveMacro(match):
return self._Expand(match, macro_stack)
return macro_ref_re.sub(_resolveMacro, text)
@ -496,9 +499,10 @@ class SourceFile(object):
# Add the ending marker.
if len(captured_lines) == 1:
result.append('//%%PDDM-EXPAND-END %s' %
captured_lines[0][directive_len:].strip())
captured_lines[0][directive_len:].strip())
else:
result.append('//%%PDDM-EXPAND-END (%s expansions)' % len(captured_lines))
result.append('//%%PDDM-EXPAND-END (%s expansions)' %
len(captured_lines))
return result
@ -669,15 +673,15 @@ def main(args):
if src_file.processed_content != src_file.original_content:
if not opts.dry_run:
print 'Updating for "%s".' % a_path
print('Updating for "%s".' % a_path)
with open(a_path, 'w') as f:
f.write(src_file.processed_content)
else:
# Special result to indicate things need updating.
print 'Update needed for "%s".' % a_path
print('Update needed for "%s".' % a_path)
result = 1
elif opts.verbose:
print 'No update for "%s".' % a_path
print('No update for "%s".' % a_path)
return result

@ -39,11 +39,15 @@ __author__ = 'robinson@google.com (Will Robinson)'
import numbers
import operator
import os.path
import sys
from google.protobuf import unittest_import_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.
# This is used to gate several fields/features that only exist
@ -51,6 +55,7 @@ from google.protobuf import descriptor_pb2
def IsProto2(message):
return message.DESCRIPTOR.syntax == "proto2"
def SetAllNonLazyFields(message):
"""Sets every non-lazy field in the message to a unique value.
@ -707,8 +712,8 @@ class NonStandardInteger(numbers.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.
Note: This is added here instead of relying on numpy or a similar library with
custom integers to limit dependencies.
Note: This is added here instead of relying on numpy or a similar library
with custom integers to limit dependencies.
"""
def __init__(self, val, error_string_on_conversion=None):
@ -845,4 +850,3 @@ class NonStandardInteger(numbers.Integral):
def __repr__(self):
return 'NonStandardInteger(%s)' % self.val

Loading…
Cancel
Save