Modernize Python 2 code to prepare for Python 3

This commit is contained in:
cclauss 2019-08-04 08:38:29 +02:00
parent e0e01d53c2
commit 2e7ce75cfd
16 changed files with 127 additions and 93 deletions

View File

@ -26,3 +26,8 @@ matrix:
exclude: exclude:
- os: linux - os: linux
compiler: clang compiler: clang
include:
- language: python
before_install: pip install flake8
before_script: true
script: flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics

View File

@ -58,6 +58,7 @@ report any problems to googlemock@googlegroups.com. You can read
http://code.google.com/p/googlemock/wiki/CookBook for more http://code.google.com/p/googlemock/wiki/CookBook for more
information. information.
""" """
from __future__ import print_function
__author__ = 'wan@google.com (Zhanyong Wan)' __author__ = 'wan@google.com (Zhanyong Wan)'
@ -119,7 +120,7 @@ def ValidateOutputDir(output_dir):
def FuseGMockH(gmock_root, output_dir): def FuseGMockH(gmock_root, output_dir):
"""Scans folder gmock_root to generate gmock/gmock.h in output_dir.""" """Scans folder gmock_root to generate gmock/gmock.h in output_dir."""
output_file = file(os.path.join(output_dir, GMOCK_H_OUTPUT), 'w') output_file = open(os.path.join(output_dir, GMOCK_H_OUTPUT), 'w')
processed_files = sets.Set() # Holds all gmock headers we've processed. processed_files = sets.Set() # Holds all gmock headers we've processed.
def ProcessFile(gmock_header_path): def ProcessFile(gmock_header_path):
@ -132,7 +133,7 @@ def FuseGMockH(gmock_root, output_dir):
processed_files.add(gmock_header_path) processed_files.add(gmock_header_path)
# Reads each line in the given gmock header. # Reads each line in the given gmock header.
for line in file(os.path.join(gmock_root, gmock_header_path), 'r'): for line in open(os.path.join(gmock_root, gmock_header_path), 'r'):
m = INCLUDE_GMOCK_FILE_REGEX.match(line) m = INCLUDE_GMOCK_FILE_REGEX.match(line)
if m: if m:
# It's '#include "gmock/..."' - let's process it recursively. # It's '#include "gmock/..."' - let's process it recursively.
@ -171,7 +172,7 @@ def FuseGMockAllCcToFile(gmock_root, output_file):
processed_files.add(gmock_source_file) processed_files.add(gmock_source_file)
# Reads each line in the given gmock source file. # Reads each line in the given gmock source file.
for line in file(os.path.join(gmock_root, gmock_source_file), 'r'): for line in open(os.path.join(gmock_root, gmock_source_file), 'r'):
m = INCLUDE_GMOCK_FILE_REGEX.match(line) m = INCLUDE_GMOCK_FILE_REGEX.match(line)
if m: if m:
# It's '#include "gmock/foo.h"'. We treat it as '#include # It's '#include "gmock/foo.h"'. We treat it as '#include
@ -204,7 +205,7 @@ def FuseGMockAllCcToFile(gmock_root, output_file):
def FuseGMockGTestAllCc(gmock_root, output_dir): def FuseGMockGTestAllCc(gmock_root, output_dir):
"""Scans folder gmock_root to generate gmock-gtest-all.cc in output_dir.""" """Scans folder gmock_root to generate gmock-gtest-all.cc in output_dir."""
output_file = file(os.path.join(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT), 'w') output_file = open(os.path.join(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT), 'w')
# First, fuse gtest-all.cc into gmock-gtest-all.cc. # First, fuse gtest-all.cc into gmock-gtest-all.cc.
gtest.FuseGTestAllCcToFile(GetGTestRootDir(gmock_root), output_file) gtest.FuseGTestAllCcToFile(GetGTestRootDir(gmock_root), output_file)
# Next, append fused gmock-all.cc to gmock-gtest-all.cc. # Next, append fused gmock-all.cc to gmock-gtest-all.cc.
@ -232,7 +233,7 @@ def main():
# fuse_gmock_files.py GMOCK_ROOT_DIR OUTPUT_DIR # fuse_gmock_files.py GMOCK_ROOT_DIR OUTPUT_DIR
FuseGMock(sys.argv[1], sys.argv[2]) FuseGMock(sys.argv[1], sys.argv[2])
else: else:
print __doc__ print(__doc__)
sys.exit(1) sys.exit(1)

View File

@ -16,6 +16,7 @@
# limitations under the License. # limitations under the License.
"""Generate an Abstract Syntax Tree (AST) for C++.""" """Generate an Abstract Syntax Tree (AST) for C++."""
from __future__ import print_function
__author__ = 'nnorwitz@google.com (Neal Norwitz)' __author__ = 'nnorwitz@google.com (Neal Norwitz)'

View File

@ -16,6 +16,7 @@
# limitations under the License. # limitations under the License.
"""Tokenize C++ source code.""" """Tokenize C++ source code."""
from __future__ import print_function
__author__ = 'nnorwitz@google.com (Neal Norwitz)' __author__ = 'nnorwitz@google.com (Neal Norwitz)'

View File

@ -16,6 +16,7 @@
# limitations under the License. # limitations under the License.
"""Generic utilities for C++ parsing.""" """Generic utilities for C++ parsing."""
from __future__ import print_function
__author__ = 'nnorwitz@google.com (Neal Norwitz)' __author__ = 'nnorwitz@google.com (Neal Norwitz)'

View File

@ -30,6 +30,7 @@
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Converts compiler's errors in code using Google Mock to plain English.""" """Converts compiler's errors in code using Google Mock to plain English."""
from __future__ import print_function
__author__ = 'wan@google.com (Zhanyong Wan)' __author__ = 'wan@google.com (Zhanyong Wan)'
@ -618,7 +619,7 @@ If you send your source code and the compiler's error messages to
win-win for us!""" % (msg, _EMAIL)) win-win for us!""" % (msg, _EMAIL))
else: else:
print ('------------------------------------------------------------') print ('------------------------------------------------------------')
print ('Your code appears to have the following',) print(('Your code appears to have the following',))
if count > 1: if count > 1:
print ('%s diseases:' % (count,)) print ('%s diseases:' % (count,))
else: else:

View File

@ -28,6 +28,7 @@ Supported version control systems:
It is important for Git/Mercurial users to specify a tree/node/branch to diff It is important for Git/Mercurial users to specify a tree/node/branch to diff
against by using the '--rev' option. against by using the '--rev' option.
""" """
from __future__ import print_function
# This code is derived from appcfg.py in the App Engine SDK (open source), # This code is derived from appcfg.py in the App Engine SDK (open source),
# and from ASPN recipe #146306. # and from ASPN recipe #146306.
@ -51,6 +52,11 @@ try:
except ImportError: except ImportError:
pass pass
try:
raw_input
except NameError:
raw_input = input
# The logging verbosity: # The logging verbosity:
# 0: Errors only. # 0: Errors only.
# 1: Status messages. # 1: Status messages.
@ -79,7 +85,7 @@ def GetEmail(prompt):
last_email = last_email_file.readline().strip("\n") last_email = last_email_file.readline().strip("\n")
last_email_file.close() last_email_file.close()
prompt += " [%s]" % last_email prompt += " [%s]" % last_email
except IOError, e: except IOError as e:
pass pass
email = raw_input(prompt + ": ").strip() email = raw_input(prompt + ": ").strip()
if email: if email:
@ -87,7 +93,7 @@ def GetEmail(prompt):
last_email_file = open(last_email_file_name, "w") last_email_file = open(last_email_file_name, "w")
last_email_file.write(email) last_email_file.write(email)
last_email_file.close() last_email_file.close()
except IOError, e: except IOError as e:
pass pass
else: else:
email = last_email email = last_email
@ -103,12 +109,12 @@ def StatusUpdate(msg):
msg: The string to print. msg: The string to print.
""" """
if verbosity > 0: if verbosity > 0:
print msg print(msg)
def ErrorExit(msg): def ErrorExit(msg):
"""Print an error message to stderr and exit.""" """Print an error message to stderr and exit."""
print >>sys.stderr, msg print(msg, file=sys.stderr)
sys.exit(1) sys.exit(1)
@ -203,7 +209,7 @@ class AbstractRpcServer(object):
response_dict = dict(x.split("=") response_dict = dict(x.split("=")
for x in response_body.split("\n") if x) for x in response_body.split("\n") if x)
return response_dict["Auth"] return response_dict["Auth"]
except urllib2.HTTPError, e: except urllib2.HTTPError as e:
if e.code == 403: if e.code == 403:
body = e.read() body = e.read()
response_dict = dict(x.split("=", 1) for x in body.split("\n") if x) response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
@ -228,7 +234,7 @@ class AbstractRpcServer(object):
(self.host, urllib.urlencode(args))) (self.host, urllib.urlencode(args)))
try: try:
response = self.opener.open(req) response = self.opener.open(req)
except urllib2.HTTPError, e: except urllib2.HTTPError as e:
response = e response = e
if (response.code != 302 or if (response.code != 302 or
response.info()["location"] != continue_location): response.info()["location"] != continue_location):
@ -255,34 +261,34 @@ class AbstractRpcServer(object):
credentials = self.auth_function() credentials = self.auth_function()
try: try:
auth_token = self._GetAuthToken(credentials[0], credentials[1]) auth_token = self._GetAuthToken(credentials[0], credentials[1])
except ClientLoginError, e: except ClientLoginError as e:
if e.reason == "BadAuthentication": if e.reason == "BadAuthentication":
print >>sys.stderr, "Invalid username or password." print("Invalid username or password.", file=sys.stderr)
continue continue
if e.reason == "CaptchaRequired": if e.reason == "CaptchaRequired":
print >>sys.stderr, ( print((
"Please go to\n" "Please go to\n"
"https://www.google.com/accounts/DisplayUnlockCaptcha\n" "https://www.google.com/accounts/DisplayUnlockCaptcha\n"
"and verify you are a human. Then try again.") "and verify you are a human. Then try again."), file=sys.stderr)
break break
if e.reason == "NotVerified": if e.reason == "NotVerified":
print >>sys.stderr, "Account not verified." print("Account not verified.", file=sys.stderr)
break break
if e.reason == "TermsNotAgreed": if e.reason == "TermsNotAgreed":
print >>sys.stderr, "User has not agreed to TOS." print("User has not agreed to TOS.", file=sys.stderr)
break break
if e.reason == "AccountDeleted": if e.reason == "AccountDeleted":
print >>sys.stderr, "The user account has been deleted." print("The user account has been deleted.", file=sys.stderr)
break break
if e.reason == "AccountDisabled": if e.reason == "AccountDisabled":
print >>sys.stderr, "The user account has been disabled." print("The user account has been disabled.", file=sys.stderr)
break break
if e.reason == "ServiceDisabled": if e.reason == "ServiceDisabled":
print >>sys.stderr, ("The user's access to the service has been " print(("The user's access to the service has been "
"disabled.") "disabled."), file=sys.stderr)
break break
if e.reason == "ServiceUnavailable": if e.reason == "ServiceUnavailable":
print >>sys.stderr, "The service is not available; try again later." print("The service is not available; try again later.", file=sys.stderr)
break break
raise raise
self._GetAuthCookie(auth_token) self._GetAuthCookie(auth_token)
@ -327,7 +333,7 @@ class AbstractRpcServer(object):
response = f.read() response = f.read()
f.close() f.close()
return response return response
except urllib2.HTTPError, e: except urllib2.HTTPError as e:
if tries > 3: if tries > 3:
raise raise
elif e.code == 401: elif e.code == 401:
@ -378,10 +384,10 @@ class HttpRpcServer(AbstractRpcServer):
pass pass
else: else:
# Create an empty cookie file with mode 600 # Create an empty cookie file with mode 600
fd = os.open(self.cookie_file, os.O_CREAT, 0600) fd = os.open(self.cookie_file, os.O_CREAT, 0o600)
os.close(fd) os.close(fd)
# Always chmod the cookie file # Always chmod the cookie file
os.chmod(self.cookie_file, 0600) os.chmod(self.cookie_file, 0o600)
else: else:
# Don't save cookies across runs of update.py. # Don't save cookies across runs of update.py.
self.cookie_jar = cookielib.CookieJar() self.cookie_jar = cookielib.CookieJar()
@ -560,7 +566,7 @@ def RunShellWithReturnCode(command, print_output=False,
line = p.stdout.readline() line = p.stdout.readline()
if not line: if not line:
break break
print line.strip("\n") print(line.strip("\n"))
output_array.append(line) output_array.append(line)
output = "".join(output_array) output = "".join(output_array)
else: else:
@ -568,7 +574,7 @@ def RunShellWithReturnCode(command, print_output=False,
p.wait() p.wait()
errout = p.stderr.read() errout = p.stderr.read()
if print_output and errout: if print_output and errout:
print >>sys.stderr, errout print(errout, file=sys.stderr)
p.stdout.close() p.stdout.close()
p.stderr.close() p.stderr.close()
return output, p.returncode return output, p.returncode
@ -614,9 +620,9 @@ class VersionControlSystem(object):
"""Show an "are you sure?" prompt if there are unknown files.""" """Show an "are you sure?" prompt if there are unknown files."""
unknown_files = self.GetUnknownFiles() unknown_files = self.GetUnknownFiles()
if unknown_files: if unknown_files:
print "The following files are not added to version control:" print("The following files are not added to version control:")
for line in unknown_files: for line in unknown_files:
print line print(line)
prompt = "Are you sure to continue?(y/N) " prompt = "Are you sure to continue?(y/N) "
answer = raw_input(prompt).strip() answer = raw_input(prompt).strip()
if answer != "y": if answer != "y":
@ -676,7 +682,7 @@ class VersionControlSystem(object):
content = "" content = ""
checksum = md5.new(content).hexdigest() checksum = md5.new(content).hexdigest()
if options.verbose > 0 and not file_too_large: if options.verbose > 0 and not file_too_large:
print "Uploading %s file for %s" % (type, filename) print("Uploading %s file for %s" % (type, filename))
url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id) url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
form_fields = [("filename", filename), form_fields = [("filename", filename),
("status", status), ("status", status),
@ -1196,7 +1202,7 @@ def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
files = [("data", "data.diff", patch[1])] files = [("data", "data.diff", patch[1])]
ctype, body = EncodeMultipartFormData(form_fields, files) ctype, body = EncodeMultipartFormData(form_fields, files)
url = "/%d/upload_patch/%d" % (int(issue), int(patchset)) url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
print "Uploading patch for " + patch[0] print("Uploading patch for " + patch[0])
response_body = rpc_server.Send(url, body, content_type=ctype) response_body = rpc_server.Send(url, body, content_type=ctype)
lines = response_body.splitlines() lines = response_body.splitlines()
if not lines or lines[0] != "OK": if not lines or lines[0] != "OK":
@ -1223,7 +1229,8 @@ def GuessVCS(options):
out, returncode = RunShellWithReturnCode(["hg", "root"]) out, returncode = RunShellWithReturnCode(["hg", "root"])
if returncode == 0: if returncode == 0:
return MercurialVCS(options, out.strip()) return MercurialVCS(options, out.strip())
except OSError, (errno, message): except OSError as xxx_todo_changeme:
(errno, message) = xxx_todo_changeme.args
if errno != 2: # ENOENT -- they don't have hg installed. if errno != 2: # ENOENT -- they don't have hg installed.
raise raise
@ -1239,7 +1246,8 @@ def GuessVCS(options):
"--is-inside-work-tree"]) "--is-inside-work-tree"])
if returncode == 0: if returncode == 0:
return GitVCS(options) return GitVCS(options)
except OSError, (errno, message): except OSError as xxx_todo_changeme1:
(errno, message) = xxx_todo_changeme1.args
if errno != 2: # ENOENT -- they don't have git installed. if errno != 2: # ENOENT -- they don't have git installed.
raise raise
@ -1286,7 +1294,7 @@ def RealMain(argv, data=None):
data = vcs.GenerateDiff(args) data = vcs.GenerateDiff(args)
files = vcs.GetBaseFiles(data) files = vcs.GetBaseFiles(data)
if verbosity >= 1: if verbosity >= 1:
print "Upload server:", options.server, "(change with -s/--server)" print("Upload server:", options.server, "(change with -s/--server)")
if options.issue: if options.issue:
prompt = "Message describing this patch set: " prompt = "Message describing this patch set: "
else: else:
@ -1338,7 +1346,7 @@ def RealMain(argv, data=None):
if not options.download_base: if not options.download_base:
form_fields.append(("content_upload", "1")) form_fields.append(("content_upload", "1"))
if len(data) > MAX_UPLOAD_SIZE: if len(data) > MAX_UPLOAD_SIZE:
print "Patch is large, so uploading file patches separately." print("Patch is large, so uploading file patches separately.")
uploaded_diff_file = [] uploaded_diff_file = []
form_fields.append(("separate_patches", "1")) form_fields.append(("separate_patches", "1"))
else: else:
@ -1378,7 +1386,7 @@ def main():
try: try:
RealMain(sys.argv) RealMain(sys.argv)
except KeyboardInterrupt: except KeyboardInterrupt:
print print()
StatusUpdate("Interrupted.") StatusUpdate("Interrupted.")
sys.exit(1) sys.exit(1)

View File

@ -55,6 +55,7 @@ problems to googletestframework@googlegroups.com. You can read
http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide for http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide for
more information. more information.
""" """
from __future__ import print_function
__author__ = 'wan@google.com (Zhanyong Wan)' __author__ = 'wan@google.com (Zhanyong Wan)'

View File

@ -45,6 +45,7 @@ predicate assertions, and writes it to file gtest_pred_impl.h in the
directory where the script is. It also generates the accompanying directory where the script is. It also generates the accompanying
unit test in file gtest_pred_impl_unittest.cc. unit test in file gtest_pred_impl_unittest.cc.
""" """
from __future__ import print_function
__author__ = 'wan@google.com (Zhanyong Wan)' __author__ = 'wan@google.com (Zhanyong Wan)'
@ -303,13 +304,13 @@ def GenerateFile(path, content):
"""Given a file path and a content string, overwrites it with the """Given a file path and a content string, overwrites it with the
given content.""" given content."""
print 'Updating file %s . . .' % path print('Updating file %s . . .' % path)
f = file(path, 'w+') f = open(path, 'w+')
print >>f, content, print(content, end=' ', file=f)
f.close() f.close()
print 'File %s has been updated.' % path print('File %s has been updated.' % path)
def GenerateHeader(n): def GenerateHeader(n):
@ -717,8 +718,8 @@ def _Main():
unit test.""" unit test."""
if len(sys.argv) != 2: if len(sys.argv) != 2:
print __doc__ print(__doc__)
print 'Author: ' + __author__ print('Author: ' + __author__)
sys.exit(1) sys.exit(1)
n = int(sys.argv[1]) n = int(sys.argv[1])

View File

@ -61,6 +61,7 @@ GRAMMAR:
| EMPTY | EMPTY
EXPRESSION has Python syntax. EXPRESSION has Python syntax.
""" """
from __future__ import print_function
__author__ = 'wan@google.com (Zhanyong Wan)' __author__ = 'wan@google.com (Zhanyong Wan)'
@ -246,7 +247,7 @@ def ParseToken(lines, pos, regex, token_type):
if m and not m.start(): if m and not m.start():
return MakeToken(lines, pos, pos + m.end(), token_type) return MakeToken(lines, pos, pos + m.end(), token_type)
else: else:
print 'ERROR: %s expected at %s.' % (token_type, pos) print('ERROR: %s expected at %s.' % (token_type, pos))
sys.exit(1) sys.exit(1)
@ -453,8 +454,8 @@ def PushFront(a_list, elem):
def PopToken(a_list, token_type=None): def PopToken(a_list, token_type=None):
token = PopFront(a_list) token = PopFront(a_list)
if token_type is not None and token.token_type != token_type: if token_type is not None and token.token_type != token_type:
print 'ERROR: %s expected at %s' % (token_type, token.start) print('ERROR: %s expected at %s' % (token_type, token.start))
print 'ERROR: %s found instead' % (token,) print('ERROR: %s found instead' % (token,))
sys.exit(1) sys.exit(1)
return token return token
@ -616,14 +617,14 @@ class Env:
if identifier == var: if identifier == var:
return value return value
print 'ERROR: meta variable %s is undefined.' % (identifier,) print('ERROR: meta variable %s is undefined.' % (identifier,))
sys.exit(1) sys.exit(1)
def EvalExp(self, exp): def EvalExp(self, exp):
try: try:
result = eval(exp.python_exp) result = eval(exp.python_exp)
except Exception, e: except Exception as e:
print 'ERROR: caught exception %s: %s' % (e.__class__.__name__, e) print('ERROR: caught exception %s: %s' % (e.__class__.__name__, e))
print ('ERROR: failed to evaluate meta expression %s at %s' % print ('ERROR: failed to evaluate meta expression %s at %s' %
(exp.python_exp, exp.token.start)) (exp.python_exp, exp.token.start))
sys.exit(1) sys.exit(1)
@ -634,7 +635,7 @@ class Env:
if identifier == var: if identifier == var:
return (lower, upper) return (lower, upper)
print 'ERROR: range %s is undefined.' % (identifier,) print('ERROR: range %s is undefined.' % (identifier,))
sys.exit(1) sys.exit(1)
@ -694,8 +695,8 @@ def RunAtomicCode(env, node, output):
elif isinstance(node, CodeNode): elif isinstance(node, CodeNode):
RunCode(env.Clone(), node, output) RunCode(env.Clone(), node, output)
else: else:
print 'BAD' print('BAD')
print node print(node)
sys.exit(1) sys.exit(1)
@ -830,19 +831,19 @@ def ConvertFromPumpSource(src_text):
def main(argv): def main(argv):
if len(argv) == 1: if len(argv) == 1:
print __doc__ print(__doc__)
sys.exit(1) sys.exit(1)
file_path = argv[-1] file_path = argv[-1]
output_str = ConvertFromPumpSource(file(file_path, 'r').read()) output_str = ConvertFromPumpSource(open(file_path, 'r').read())
if file_path.endswith('.pump'): if file_path.endswith('.pump'):
output_file_path = file_path[:-5] output_file_path = file_path[:-5]
else: else:
output_file_path = '-' output_file_path = '-'
if output_file_path == '-': if output_file_path == '-':
print output_str, print(output_str, end=' ')
else: else:
output_file = file(output_file_path, 'w') output_file = open(output_file_path, 'w')
output_file.write('// This file was GENERATED by command:\n') output_file.write('// This file was GENERATED by command:\n')
output_file.write('// %s %s\n' % output_file.write('// %s %s\n' %
(os.path.basename(__file__), os.path.basename(file_path))) (os.path.basename(__file__), os.path.basename(file_path)))

View File

@ -60,6 +60,7 @@ EXAMPLE
$ svn diff # verify the file contents $ svn diff # verify the file contents
$ svn commit -m "release wiki pages for v2.6" $ svn commit -m "release wiki pages for v2.6"
""" """
from __future__ import print_function
__author__ = 'wan@google.com (Zhanyong Wan)' __author__ = 'wan@google.com (Zhanyong Wan)'
@ -127,11 +128,11 @@ class WikiBrancher(object):
def BranchFiles(self): def BranchFiles(self):
"""Branches the .wiki files needed to be branched.""" """Branches the .wiki files needed to be branched."""
print 'Branching %d .wiki files:' % (len(self.files_to_branch),) print('Branching %d .wiki files:' % (len(self.files_to_branch),))
os.chdir(self.wiki_dir) os.chdir(self.wiki_dir)
for f in self.files_to_branch: for f in self.files_to_branch:
command = 'svn cp %s %s%s' % (f, self.version_prefix, f) command = 'svn cp %s %s%s' % (f, self.version_prefix, f)
print command print(command)
os.system(command) os.system(command)
def UpdateLinksInBranchedFiles(self): def UpdateLinksInBranchedFiles(self):
@ -139,10 +140,10 @@ class WikiBrancher(object):
for f in self.files_to_branch: for f in self.files_to_branch:
source_file = os.path.join(self.wiki_dir, f) source_file = os.path.join(self.wiki_dir, f)
versioned_file = os.path.join(self.wiki_dir, self.version_prefix + f) versioned_file = os.path.join(self.wiki_dir, self.version_prefix + f)
print 'Updating links in %s.' % (versioned_file,) print('Updating links in %s.' % (versioned_file,))
text = file(source_file, 'r').read() text = open(source_file, 'r').read()
new_text = self.search_for_re.sub(self.replace_with, text) new_text = self.search_for_re.sub(self.replace_with, text)
file(versioned_file, 'w').write(new_text) open(versioned_file, 'w').write(new_text)
def main(): def main():

View File

@ -28,6 +28,7 @@ Supported version control systems:
It is important for Git/Mercurial users to specify a tree/node/branch to diff It is important for Git/Mercurial users to specify a tree/node/branch to diff
against by using the '--rev' option. against by using the '--rev' option.
""" """
from __future__ import print_function
# This code is derived from appcfg.py in the App Engine SDK (open source), # This code is derived from appcfg.py in the App Engine SDK (open source),
# and from ASPN recipe #146306. # and from ASPN recipe #146306.
@ -51,6 +52,11 @@ try:
except ImportError: except ImportError:
pass pass
try:
raw_input
except NameError:
raw_input = input
# The logging verbosity: # The logging verbosity:
# 0: Errors only. # 0: Errors only.
# 1: Status messages. # 1: Status messages.
@ -79,7 +85,7 @@ def GetEmail(prompt):
last_email = last_email_file.readline().strip("\n") last_email = last_email_file.readline().strip("\n")
last_email_file.close() last_email_file.close()
prompt += " [%s]" % last_email prompt += " [%s]" % last_email
except IOError, e: except IOError as e:
pass pass
email = raw_input(prompt + ": ").strip() email = raw_input(prompt + ": ").strip()
if email: if email:
@ -87,7 +93,7 @@ def GetEmail(prompt):
last_email_file = open(last_email_file_name, "w") last_email_file = open(last_email_file_name, "w")
last_email_file.write(email) last_email_file.write(email)
last_email_file.close() last_email_file.close()
except IOError, e: except IOError as e:
pass pass
else: else:
email = last_email email = last_email
@ -103,12 +109,12 @@ def StatusUpdate(msg):
msg: The string to print. msg: The string to print.
""" """
if verbosity > 0: if verbosity > 0:
print msg print(msg)
def ErrorExit(msg): def ErrorExit(msg):
"""Print an error message to stderr and exit.""" """Print an error message to stderr and exit."""
print >>sys.stderr, msg print(msg, file=sys.stderr)
sys.exit(1) sys.exit(1)
@ -203,7 +209,7 @@ class AbstractRpcServer(object):
response_dict = dict(x.split("=") response_dict = dict(x.split("=")
for x in response_body.split("\n") if x) for x in response_body.split("\n") if x)
return response_dict["Auth"] return response_dict["Auth"]
except urllib2.HTTPError, e: except urllib2.HTTPError as e:
if e.code == 403: if e.code == 403:
body = e.read() body = e.read()
response_dict = dict(x.split("=", 1) for x in body.split("\n") if x) response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
@ -228,7 +234,7 @@ class AbstractRpcServer(object):
(self.host, urllib.urlencode(args))) (self.host, urllib.urlencode(args)))
try: try:
response = self.opener.open(req) response = self.opener.open(req)
except urllib2.HTTPError, e: except urllib2.HTTPError as e:
response = e response = e
if (response.code != 302 or if (response.code != 302 or
response.info()["location"] != continue_location): response.info()["location"] != continue_location):
@ -255,34 +261,34 @@ class AbstractRpcServer(object):
credentials = self.auth_function() credentials = self.auth_function()
try: try:
auth_token = self._GetAuthToken(credentials[0], credentials[1]) auth_token = self._GetAuthToken(credentials[0], credentials[1])
except ClientLoginError, e: except ClientLoginError as e:
if e.reason == "BadAuthentication": if e.reason == "BadAuthentication":
print >>sys.stderr, "Invalid username or password." print("Invalid username or password.", file=sys.stderr)
continue continue
if e.reason == "CaptchaRequired": if e.reason == "CaptchaRequired":
print >>sys.stderr, ( print((
"Please go to\n" "Please go to\n"
"https://www.google.com/accounts/DisplayUnlockCaptcha\n" "https://www.google.com/accounts/DisplayUnlockCaptcha\n"
"and verify you are a human. Then try again.") "and verify you are a human. Then try again."), file=sys.stderr)
break break
if e.reason == "NotVerified": if e.reason == "NotVerified":
print >>sys.stderr, "Account not verified." print("Account not verified.", file=sys.stderr)
break break
if e.reason == "TermsNotAgreed": if e.reason == "TermsNotAgreed":
print >>sys.stderr, "User has not agreed to TOS." print("User has not agreed to TOS.", file=sys.stderr)
break break
if e.reason == "AccountDeleted": if e.reason == "AccountDeleted":
print >>sys.stderr, "The user account has been deleted." print("The user account has been deleted.", file=sys.stderr)
break break
if e.reason == "AccountDisabled": if e.reason == "AccountDisabled":
print >>sys.stderr, "The user account has been disabled." print("The user account has been disabled.", file=sys.stderr)
break break
if e.reason == "ServiceDisabled": if e.reason == "ServiceDisabled":
print >>sys.stderr, ("The user's access to the service has been " print(("The user's access to the service has been "
"disabled.") "disabled."), file=sys.stderr)
break break
if e.reason == "ServiceUnavailable": if e.reason == "ServiceUnavailable":
print >>sys.stderr, "The service is not available; try again later." print("The service is not available; try again later.", file=sys.stderr)
break break
raise raise
self._GetAuthCookie(auth_token) self._GetAuthCookie(auth_token)
@ -327,7 +333,7 @@ class AbstractRpcServer(object):
response = f.read() response = f.read()
f.close() f.close()
return response return response
except urllib2.HTTPError, e: except urllib2.HTTPError as e:
if tries > 3: if tries > 3:
raise raise
elif e.code == 401: elif e.code == 401:
@ -378,10 +384,10 @@ class HttpRpcServer(AbstractRpcServer):
pass pass
else: else:
# Create an empty cookie file with mode 600 # Create an empty cookie file with mode 600
fd = os.open(self.cookie_file, os.O_CREAT, 0600) fd = os.open(self.cookie_file, os.O_CREAT, 0o600)
os.close(fd) os.close(fd)
# Always chmod the cookie file # Always chmod the cookie file
os.chmod(self.cookie_file, 0600) os.chmod(self.cookie_file, 0o600)
else: else:
# Don't save cookies across runs of update.py. # Don't save cookies across runs of update.py.
self.cookie_jar = cookielib.CookieJar() self.cookie_jar = cookielib.CookieJar()
@ -560,7 +566,7 @@ def RunShellWithReturnCode(command, print_output=False,
line = p.stdout.readline() line = p.stdout.readline()
if not line: if not line:
break break
print line.strip("\n") print(line.strip("\n"))
output_array.append(line) output_array.append(line)
output = "".join(output_array) output = "".join(output_array)
else: else:
@ -568,7 +574,7 @@ def RunShellWithReturnCode(command, print_output=False,
p.wait() p.wait()
errout = p.stderr.read() errout = p.stderr.read()
if print_output and errout: if print_output and errout:
print >>sys.stderr, errout print(errout, file=sys.stderr)
p.stdout.close() p.stdout.close()
p.stderr.close() p.stderr.close()
return output, p.returncode return output, p.returncode
@ -614,9 +620,9 @@ class VersionControlSystem(object):
"""Show an "are you sure?" prompt if there are unknown files.""" """Show an "are you sure?" prompt if there are unknown files."""
unknown_files = self.GetUnknownFiles() unknown_files = self.GetUnknownFiles()
if unknown_files: if unknown_files:
print "The following files are not added to version control:" print("The following files are not added to version control:")
for line in unknown_files: for line in unknown_files:
print line print(line)
prompt = "Are you sure to continue?(y/N) " prompt = "Are you sure to continue?(y/N) "
answer = raw_input(prompt).strip() answer = raw_input(prompt).strip()
if answer != "y": if answer != "y":
@ -676,7 +682,7 @@ class VersionControlSystem(object):
content = "" content = ""
checksum = md5.new(content).hexdigest() checksum = md5.new(content).hexdigest()
if options.verbose > 0 and not file_too_large: if options.verbose > 0 and not file_too_large:
print "Uploading %s file for %s" % (type, filename) print("Uploading %s file for %s" % (type, filename))
url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id) url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
form_fields = [("filename", filename), form_fields = [("filename", filename),
("status", status), ("status", status),
@ -1196,7 +1202,7 @@ def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
files = [("data", "data.diff", patch[1])] files = [("data", "data.diff", patch[1])]
ctype, body = EncodeMultipartFormData(form_fields, files) ctype, body = EncodeMultipartFormData(form_fields, files)
url = "/%d/upload_patch/%d" % (int(issue), int(patchset)) url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
print "Uploading patch for " + patch[0] print("Uploading patch for " + patch[0])
response_body = rpc_server.Send(url, body, content_type=ctype) response_body = rpc_server.Send(url, body, content_type=ctype)
lines = response_body.splitlines() lines = response_body.splitlines()
if not lines or lines[0] != "OK": if not lines or lines[0] != "OK":
@ -1223,7 +1229,8 @@ def GuessVCS(options):
out, returncode = RunShellWithReturnCode(["hg", "root"]) out, returncode = RunShellWithReturnCode(["hg", "root"])
if returncode == 0: if returncode == 0:
return MercurialVCS(options, out.strip()) return MercurialVCS(options, out.strip())
except OSError, (errno, message): except OSError as xxx_todo_changeme:
(errno, message) = xxx_todo_changeme.args
if errno != 2: # ENOENT -- they don't have hg installed. if errno != 2: # ENOENT -- they don't have hg installed.
raise raise
@ -1239,7 +1246,8 @@ def GuessVCS(options):
"--is-inside-work-tree"]) "--is-inside-work-tree"])
if returncode == 0: if returncode == 0:
return GitVCS(options) return GitVCS(options)
except OSError, (errno, message): except OSError as xxx_todo_changeme1:
(errno, message) = xxx_todo_changeme1.args
if errno != 2: # ENOENT -- they don't have git installed. if errno != 2: # ENOENT -- they don't have git installed.
raise raise
@ -1286,7 +1294,7 @@ def RealMain(argv, data=None):
data = vcs.GenerateDiff(args) data = vcs.GenerateDiff(args)
files = vcs.GetBaseFiles(data) files = vcs.GetBaseFiles(data)
if verbosity >= 1: if verbosity >= 1:
print "Upload server:", options.server, "(change with -s/--server)" print("Upload server:", options.server, "(change with -s/--server)")
if options.issue: if options.issue:
prompt = "Message describing this patch set: " prompt = "Message describing this patch set: "
else: else:
@ -1338,7 +1346,7 @@ def RealMain(argv, data=None):
if not options.download_base: if not options.download_base:
form_fields.append(("content_upload", "1")) form_fields.append(("content_upload", "1"))
if len(data) > MAX_UPLOAD_SIZE: if len(data) > MAX_UPLOAD_SIZE:
print "Patch is large, so uploading file patches separately." print("Patch is large, so uploading file patches separately.")
uploaded_diff_file = [] uploaded_diff_file = []
form_fields.append(("separate_patches", "1")) form_fields.append(("separate_patches", "1"))
else: else:
@ -1378,7 +1386,7 @@ def main():
try: try:
RealMain(sys.argv) RealMain(sys.argv)
except KeyboardInterrupt: except KeyboardInterrupt:
print print()
StatusUpdate("Interrupted.") StatusUpdate("Interrupted.")
sys.exit(1) sys.exit(1)

View File

@ -30,6 +30,7 @@
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Verifies that Google Test correctly parses environment variables.""" """Verifies that Google Test correctly parses environment variables."""
from __future__ import print_function
__author__ = 'wan@google.com (Zhanyong Wan)' __author__ = 'wan@google.com (Zhanyong Wan)'

View File

@ -34,6 +34,7 @@
This script invokes gtest_throw_on_failure_test_ (a program written with This script invokes gtest_throw_on_failure_test_ (a program written with
Google Test) with different environments and command line flags. Google Test) with different environments and command line flags.
""" """
from __future__ import print_function
__author__ = 'wan@google.com (Zhanyong Wan)' __author__ = 'wan@google.com (Zhanyong Wan)'

View File

@ -30,6 +30,7 @@
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Verifies that Google Test warns the user when not initialized properly.""" """Verifies that Google Test warns the user when not initialized properly."""
from __future__ import print_function
__author__ = 'wan@google.com (Zhanyong Wan)' __author__ = 'wan@google.com (Zhanyong Wan)'

View File

@ -48,13 +48,14 @@
3. No ")" character exists between the opening "(" and closing ")" of 3. No ")" character exists between the opening "(" and closing ")" of
AC_INIT, including in comments and character strings. AC_INIT, including in comments and character strings.
""" """
from __future__ import print_function
import sys import sys
import re import re
# Read the command line argument (the output directory for Version.h) # Read the command line argument (the output directory for Version.h)
if (len(sys.argv) < 3): if (len(sys.argv) < 3):
print "Usage: versiongenerate.py input_dir output_dir" print("Usage: versiongenerate.py input_dir output_dir")
sys.exit(1) sys.exit(1)
else: else:
input_dir = sys.argv[1] input_dir = sys.argv[1]