Skip to content

Commit 624bee9

Browse files
committed
Merge #11881: Remove Python2 support
1874058 Make base58 python contrib code work with python3 (Evan Klitzke) bc6fdf2 Change all python files to use Python3 (John Newbery) Pull request description: Following discussion here: bitcoin/bitcoin#11843 (comment) It's easier for maintainers if all python tools/scripts support only a single version of Python. There are only a few scripts that aren't explicitly python3 at this point, so this PR changes those remaining scripts to explicitly require python3. Tree-SHA512: 5d38eef6e0fc7d8515e23a1f4c75e8b4160fd0fe23cba52a1f41689b114e54a9e503e0724829e8b41982ef98f2d113df80d9e238213b74f09ceaed0344a19e24
2 parents 0d8fc8d + 1874058 commit 624bee9

13 files changed

+80
-87
lines changed

contrib/devtools/check-doc.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
22
# Copyright (c) 2015-2017 The Bitcoin Core developers
33
# Distributed under the MIT software license, see the accompanying
44
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
@@ -16,29 +16,29 @@
1616

1717
FOLDER_GREP = 'src'
1818
FOLDER_TEST = 'src/test/'
19-
CMD_ROOT_DIR = '`git rev-parse --show-toplevel`/%s' % FOLDER_GREP
20-
CMD_GREP_ARGS = r"egrep -r -I '(map(Multi)?Args(\.count\(|\[)|Get(Bool)?Arg\()\"\-[^\"]+?\"' %s | grep -v '%s'" % (CMD_ROOT_DIR, FOLDER_TEST)
21-
CMD_GREP_DOCS = r"egrep -r -I 'HelpMessageOpt\(\"\-[^\"=]+?(=|\")' %s" % (CMD_ROOT_DIR)
19+
CMD_ROOT_DIR = '`git rev-parse --show-toplevel`/{}'.format(FOLDER_GREP)
20+
CMD_GREP_ARGS = r"egrep -r -I '(map(Multi)?Args(\.count\(|\[)|Get(Bool)?Arg\()\"\-[^\"]+?\"' {} | grep -v '{}'".format(CMD_ROOT_DIR, FOLDER_TEST)
21+
CMD_GREP_DOCS = r"egrep -r -I 'HelpMessageOpt\(\"\-[^\"=]+?(=|\")' {}".format(CMD_ROOT_DIR)
2222
REGEX_ARG = re.compile(r'(?:map(?:Multi)?Args(?:\.count\(|\[)|Get(?:Bool)?Arg\()\"(\-[^\"]+?)\"')
2323
REGEX_DOC = re.compile(r'HelpMessageOpt\(\"(\-[^\"=]+?)(?:=|\")')
2424
# list unsupported, deprecated and duplicate args as they need no documentation
2525
SET_DOC_OPTIONAL = set(['-rpcssl', '-benchmark', '-h', '-help', '-socks', '-tor', '-debugnet', '-whitelistalwaysrelay', '-prematurewitness', '-walletprematurewitness', '-promiscuousmempoolflags', '-blockminsize', '-dbcrashratio', '-forcecompactdb', '-usehd'])
2626

2727
def main():
28-
used = check_output(CMD_GREP_ARGS, shell=True)
29-
docd = check_output(CMD_GREP_DOCS, shell=True)
28+
used = check_output(CMD_GREP_ARGS, shell=True, universal_newlines=True)
29+
docd = check_output(CMD_GREP_DOCS, shell=True, universal_newlines=True)
3030

3131
args_used = set(re.findall(REGEX_ARG,used))
3232
args_docd = set(re.findall(REGEX_DOC,docd)).union(SET_DOC_OPTIONAL)
3333
args_need_doc = args_used.difference(args_docd)
3434
args_unknown = args_docd.difference(args_used)
3535

36-
print "Args used : %s" % len(args_used)
37-
print "Args documented : %s" % len(args_docd)
38-
print "Args undocumented: %s" % len(args_need_doc)
39-
print args_need_doc
40-
print "Args unknown : %s" % len(args_unknown)
41-
print args_unknown
36+
print("Args used : {}".format(len(args_used)))
37+
print("Args documented : {}".format(len(args_docd)))
38+
print("Args undocumented: {}".format(len(args_need_doc)))
39+
print(args_need_doc)
40+
print("Args unknown : {}".format(len(args_unknown)))
41+
print(args_unknown)
4242

4343
sys.exit(len(args_need_doc))
4444

contrib/devtools/clang-format-diff.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
22
#
33
#===- clang-format-diff.py - ClangFormat Diff Reformatter ----*- python -*--===#
44
#
@@ -69,10 +69,10 @@
6969

7070
import argparse
7171
import difflib
72+
import io
7273
import re
7374
import string
7475
import subprocess
75-
import StringIO
7676
import sys
7777

7878

@@ -133,30 +133,33 @@ def main():
133133
['-lines', str(start_line) + ':' + str(end_line)])
134134

135135
# Reformat files containing changes in place.
136-
for filename, lines in lines_by_file.iteritems():
136+
for filename, lines in lines_by_file.items():
137137
if args.i and args.verbose:
138-
print 'Formatting', filename
138+
print('Formatting {}'.format(filename))
139139
command = [binary, filename]
140140
if args.i:
141141
command.append('-i')
142142
if args.sort_includes:
143143
command.append('-sort-includes')
144144
command.extend(lines)
145145
command.extend(['-style=file', '-fallback-style=none'])
146-
p = subprocess.Popen(command, stdout=subprocess.PIPE,
147-
stderr=None, stdin=subprocess.PIPE)
146+
p = subprocess.Popen(command,
147+
stdout=subprocess.PIPE,
148+
stderr=None,
149+
stdin=subprocess.PIPE,
150+
universal_newlines=True)
148151
stdout, stderr = p.communicate()
149152
if p.returncode != 0:
150153
sys.exit(p.returncode)
151154

152155
if not args.i:
153156
with open(filename) as f:
154157
code = f.readlines()
155-
formatted_code = StringIO.StringIO(stdout).readlines()
158+
formatted_code = io.StringIO(stdout).readlines()
156159
diff = difflib.unified_diff(code, formatted_code,
157160
filename, filename,
158161
'(before formatting)', '(after formatting)')
159-
diff_string = string.join(diff, '')
162+
diff_string = ''.join(diff)
160163
if len(diff_string) > 0:
161164
sys.stdout.write(diff_string)
162165

contrib/devtools/optimize-pngs.py

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
22
# Copyright (c) 2014-2017 The Bitcoin Core developers
33
# Distributed under the MIT software license, see the accompanying
44
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
@@ -10,7 +10,7 @@
1010
import sys
1111
import subprocess
1212
import hashlib
13-
from PIL import Image
13+
from PIL import Image # pip3 install Pillow
1414

1515
def file_hash(filename):
1616
'''Return hash of raw file contents'''
@@ -27,7 +27,7 @@ def content_hash(filename):
2727
pngcrush = 'pngcrush'
2828
git = 'git'
2929
folders = ["src/qt/res/movies", "src/qt/res/icons", "share/pixmaps"]
30-
basePath = subprocess.check_output([git, 'rev-parse', '--show-toplevel']).rstrip('\n')
30+
basePath = subprocess.check_output([git, 'rev-parse', '--show-toplevel'], universal_newlines=True).rstrip('\n')
3131
totalSaveBytes = 0
3232
noHashChange = True
3333

@@ -37,42 +37,40 @@ def content_hash(filename):
3737
for file in os.listdir(absFolder):
3838
extension = os.path.splitext(file)[1]
3939
if extension.lower() == '.png':
40-
print("optimizing "+file+"..."),
40+
print("optimizing {}...".format(file), end =' ')
4141
file_path = os.path.join(absFolder, file)
4242
fileMetaMap = {'file' : file, 'osize': os.path.getsize(file_path), 'sha256Old' : file_hash(file_path)}
4343
fileMetaMap['contentHashPre'] = content_hash(file_path)
4444

45-
pngCrushOutput = ""
4645
try:
47-
pngCrushOutput = subprocess.check_output(
48-
[pngcrush, "-brute", "-ow", "-rem", "gAMA", "-rem", "cHRM", "-rem", "iCCP", "-rem", "sRGB", "-rem", "alla", "-rem", "text", file_path],
49-
stderr=subprocess.STDOUT).rstrip('\n')
46+
subprocess.call([pngcrush, "-brute", "-ow", "-rem", "gAMA", "-rem", "cHRM", "-rem", "iCCP", "-rem", "sRGB", "-rem", "alla", "-rem", "text", file_path],
47+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
5048
except:
51-
print "pngcrush is not installed, aborting..."
49+
print("pngcrush is not installed, aborting...")
5250
sys.exit(0)
5351

5452
#verify
55-
if "Not a PNG file" in subprocess.check_output([pngcrush, "-n", "-v", file_path], stderr=subprocess.STDOUT):
56-
print "PNG file "+file+" is corrupted after crushing, check out pngcursh version"
53+
if "Not a PNG file" in subprocess.check_output([pngcrush, "-n", "-v", file_path], stderr=subprocess.STDOUT, universal_newlines=True):
54+
print("PNG file "+file+" is corrupted after crushing, check out pngcursh version")
5755
sys.exit(1)
5856

5957
fileMetaMap['sha256New'] = file_hash(file_path)
6058
fileMetaMap['contentHashPost'] = content_hash(file_path)
6159

6260
if fileMetaMap['contentHashPre'] != fileMetaMap['contentHashPost']:
63-
print "Image contents of PNG file "+file+" before and after crushing don't match"
61+
print("Image contents of PNG file {} before and after crushing don't match".format(file))
6462
sys.exit(1)
6563

6664
fileMetaMap['psize'] = os.path.getsize(file_path)
6765
outputArray.append(fileMetaMap)
68-
print("done\n"),
66+
print("done")
6967

70-
print "summary:\n+++++++++++++++++"
68+
print("summary:\n+++++++++++++++++")
7169
for fileDict in outputArray:
7270
oldHash = fileDict['sha256Old']
7371
newHash = fileDict['sha256New']
7472
totalSaveBytes += fileDict['osize'] - fileDict['psize']
7573
noHashChange = noHashChange and (oldHash == newHash)
76-
print fileDict['file']+"\n size diff from: "+str(fileDict['osize'])+" to: "+str(fileDict['psize'])+"\n old sha256: "+oldHash+"\n new sha256: "+newHash+"\n"
74+
print(fileDict['file']+"\n size diff from: "+str(fileDict['osize'])+" to: "+str(fileDict['psize'])+"\n old sha256: "+oldHash+"\n new sha256: "+newHash+"\n")
7775

78-
print "completed. Checksum stable: "+str(noHashChange)+". Total reduction: "+str(totalSaveBytes)+" bytes"
76+
print("completed. Checksum stable: "+str(noHashChange)+". Total reduction: "+str(totalSaveBytes)+" bytes")

contrib/devtools/security-check.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
22
# Copyright (c) 2015-2017 The Bitcoin Core developers
33
# Distributed under the MIT software license, see the accompanying
44
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
@@ -8,7 +8,6 @@
88
Otherwise the exit status will be 1 and it will log which executables failed which checks.
99
Needs `readelf` (for ELF) and `objdump` (for PE).
1010
'''
11-
from __future__ import division,print_function,unicode_literals
1211
import subprocess
1312
import sys
1413
import os

contrib/devtools/symbol-check.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
22
# Copyright (c) 2014 Wladimir J. van der Laan
33
# Distributed under the MIT software license, see the accompanying
44
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
@@ -11,7 +11,6 @@
1111
1212
find ../gitian-builder/build -type f -executable | xargs python contrib/devtools/symbol-check.py
1313
'''
14-
from __future__ import division, print_function, unicode_literals
1514
import subprocess
1615
import re
1716
import sys

contrib/devtools/update-translations.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
22
# Copyright (c) 2014 Wladimir J. van der Laan
33
# Distributed under the MIT software license, see the accompanying
44
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
@@ -15,7 +15,6 @@
1515
TODO:
1616
- auto-add new translations to the build system according to the translation process
1717
'''
18-
from __future__ import division, print_function
1918
import subprocess
2019
import re
2120
import sys

contrib/macdeploy/custom_dsstore.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
#!/usr/bin/env python
1+
#!/usr/bin/env python3
22
# Copyright (c) 2013-2016 The Bitcoin Core developers
33
# Distributed under the MIT software license, see the accompanying
44
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
5-
from __future__ import division,print_function,unicode_literals
65
import biplist
76
from ds_store import DSStore
87
from mac_alias import Alias

contrib/macdeploy/macdeployqtplus

Lines changed: 5 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
#!/usr/bin/env python
2-
from __future__ import division, print_function, unicode_literals
1+
#!/usr/bin/env python3
32
#
43
# Copyright (C) 2011 Patrick "p2k" Schneider <[email protected]>
54
#
@@ -203,15 +202,15 @@ def getFrameworks(binaryPath, verbose):
203202
if verbose >= 3:
204203
print("Inspecting with otool: " + binaryPath)
205204
otoolbin=os.getenv("OTOOL", "otool")
206-
otool = subprocess.Popen([otoolbin, "-L", binaryPath], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
205+
otool = subprocess.Popen([otoolbin, "-L", binaryPath], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
207206
o_stdout, o_stderr = otool.communicate()
208207
if otool.returncode != 0:
209208
if verbose >= 1:
210209
sys.stderr.write(o_stderr)
211210
sys.stderr.flush()
212211
raise RuntimeError("otool failed with return code %d" % otool.returncode)
213212

214-
otoolLines = o_stdout.decode().split("\n")
213+
otoolLines = o_stdout.split("\n")
215214
otoolLines.pop(0) # First line is the inspected binary
216215
if ".framework" in binaryPath or binaryPath.endswith(".dylib"):
217216
otoolLines.pop(0) # Frameworks and dylibs list themselves as a dependency.
@@ -714,22 +713,6 @@ elif config.sign:
714713

715714
if config.dmg is not None:
716715

717-
#Patch in check_output for Python 2.6
718-
if "check_output" not in dir( subprocess ):
719-
def f(*popenargs, **kwargs):
720-
if 'stdout' in kwargs:
721-
raise ValueError('stdout argument not allowed, it will be overridden.')
722-
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
723-
output, unused_err = process.communicate()
724-
retcode = process.poll()
725-
if retcode:
726-
cmd = kwargs.get("args")
727-
if cmd is None:
728-
cmd = popenargs[0]
729-
raise CalledProcessError(retcode, cmd)
730-
return output
731-
subprocess.check_output = f
732-
733716
def runHDIUtil(verb, image_basename, **kwargs):
734717
hdiutil_args = ["hdiutil", verb, image_basename + ".dmg"]
735718
if "capture_stdout" in kwargs:
@@ -747,7 +730,7 @@ if config.dmg is not None:
747730
if not value is True:
748731
hdiutil_args.append(str(value))
749732

750-
return run(hdiutil_args)
733+
return run(hdiutil_args, universal_newlines=True)
751734

752735
if verbose >= 2:
753736
if fancy is None:
@@ -789,7 +772,7 @@ if config.dmg is not None:
789772
except subprocess.CalledProcessError as e:
790773
sys.exit(e.returncode)
791774

792-
m = re.search("/Volumes/(.+$)", output.decode())
775+
m = re.search("/Volumes/(.+$)", output)
793776
disk_root = m.group(0)
794777
disk_name = m.group(1)
795778

contrib/testgen/base58.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ def b58encode(v):
2828
"""
2929
long_value = 0
3030
for (i, c) in enumerate(v[::-1]):
31-
long_value += (256**i) * ord(c)
31+
if isinstance(c, str):
32+
c = ord(c)
33+
long_value += (256**i) * c
3234

3335
result = ''
3436
while long_value >= __b58base:
@@ -41,7 +43,7 @@ def b58encode(v):
4143
# leading 0-bytes in the input become leading-1s
4244
nPad = 0
4345
for c in v:
44-
if c == '\0': nPad += 1
46+
if c == 0: nPad += 1
4547
else: break
4648

4749
return (__b58chars[0]*nPad) + result
@@ -50,8 +52,10 @@ def b58decode(v, length = None):
5052
""" decode v into a string of len bytes
5153
"""
5254
long_value = 0
53-
for (i, c) in enumerate(v[::-1]):
54-
long_value += __b58chars.find(c) * (__b58base**i)
55+
for i, c in enumerate(v[::-1]):
56+
pos = __b58chars.find(c)
57+
assert pos != -1
58+
long_value += pos * (__b58base**i)
5559

5660
result = bytes()
5761
while long_value >= 256:
@@ -62,10 +66,12 @@ def b58decode(v, length = None):
6266

6367
nPad = 0
6468
for c in v:
65-
if c == __b58chars[0]: nPad += 1
66-
else: break
69+
if c == __b58chars[0]:
70+
nPad += 1
71+
continue
72+
break
6773

68-
result = chr(0)*nPad + result
74+
result = bytes(nPad) + result
6975
if length is not None and len(result) != length:
7076
return None
7177

0 commit comments

Comments
 (0)