Skip to content

Commit f168237

Browse files
authored
Merge pull request #667 from cmonr/py3-support
Added python3 compatability
2 parents 56f59d6 + abe79ee commit f168237

File tree

6 files changed

+82
-87
lines changed

6 files changed

+82
-87
lines changed

.circleci/config.yml

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -123,23 +123,9 @@ jobs:
123123
- run: cd .tests/new-test && mbed compile --source=. --source=mbed-os/TESTS/integration/basic -j 0
124124
- run: cd .tests/new-test && mbed test --compile -n mbed-os-tests-integration-basic -j 0
125125

126-
- run: cd .tests && mbed import https://developer.mbed.org/teams/Morpheus/code/mbed-Client-Morpheus-hg hg-test
127-
- run: cd .tests/hg-test && mbed ls
128-
- run: cd .tests/hg-test && mbed releases -r
129-
- run: cd .tests/hg-test && mbed update b02527cafcde8612ff051fea57e9975aca598807 --clean
130-
- run: cd .tests/hg-test && mbed update --clean
131-
- run: cd .tests/hg-test && mbed compile -j 0
132-
133-
- run: cd .tests && mbed import https://developer.mbed.org/users/samux/code/USBSerial_HelloWorld bld-test
134-
- run: cd .tests/bld-test && mbed ls
135-
- run: cd .tests/bld-test && mbed releases -r
136-
- run: cd .tests/bld-test/mbed && mbed update 85 --clean
137-
- run: cd .tests/bld-test && mbed update --clean
138-
- run: cd .tests/bld-test && mbed compile -m LPC1768 -j 0
139-
140126
workflows:
141127
version: 2
142128
build:
143129
jobs:
144130
- py2
145-
#- py3
131+
- py3

circle_tests.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
1414
# either express or implied.
1515

16+
from __future__ import print_function
17+
1618
import os
1719
import sys
1820
import subprocess

mbed/mbed.py

100644100755
Lines changed: 55 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/env python2
1+
#!/usr/bin/env python
22

33
# Copyright (c) 2016 ARM Limited, All Rights Reserved
44
# SPDX-License-Identifier: Apache-2.0
@@ -18,6 +18,18 @@
1818
# pylint: disable=too-many-nested-blocks, too-many-public-methods, too-many-instance-attributes, too-many-statements
1919
# pylint: disable=invalid-name, missing-docstring, bad-continuation
2020

21+
from __future__ import print_function
22+
from future.builtins.iterators import zip
23+
from past.builtins import basestring
24+
25+
try:
26+
from urllib.parse import urlparse, quote
27+
from urllib.request import urlopen
28+
except ImportError:
29+
from urlparse import urlparse
30+
from urllib2 import urlopen
31+
from urllib import quote
32+
2133
import traceback
2234
import sys
2335
import re
@@ -28,13 +40,10 @@
2840
import stat
2941
import errno
3042
import ctypes
31-
from itertools import chain, izip, repeat
32-
from urlparse import urlparse
33-
import urllib
34-
import urllib2
35-
import zipfile
43+
from itertools import chain, repeat
3644
import argparse
3745
import tempfile
46+
import zipfile
3847

3948

4049
# Application version
@@ -184,7 +193,7 @@ def progress_cursor():
184193
progress_spinner = progress_cursor()
185194

186195
def progress():
187-
sys.stdout.write(progress_spinner.next())
196+
sys.stdout.write(next(progress_spinner))
188197
sys.stdout.flush()
189198
sys.stdout.write('\b')
190199

@@ -211,10 +220,10 @@ def popen(command, stdin=None, **kwargs):
211220
try:
212221
proc = subprocess.Popen(command, **kwargs)
213222
except OSError as e:
214-
if e[0] == errno.ENOENT:
223+
if e.args[0] == errno.ENOENT:
215224
error(
216225
"Could not execute \"%s\".\n"
217-
"Please verify that it's installed and accessible from your current path by executing \"%s\".\n" % (command[0], command[0]), e[0])
226+
"Please verify that it's installed and accessible from your current path by executing \"%s\".\n" % (command[0], command[0]), e.args[0])
218227
else:
219228
raise e
220229

@@ -227,10 +236,10 @@ def pquery(command, output_callback=None, stdin=None, **kwargs):
227236
try:
228237
proc = subprocess.Popen(command, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
229238
except OSError as e:
230-
if e[0] == errno.ENOENT:
239+
if e.args[0] == errno.ENOENT:
231240
error(
232241
"Could not execute \"%s\".\n"
233-
"Please verify that it's installed and accessible from your current path by executing \"%s\".\n" % (command[0], command[0]), e[0])
242+
"Please verify that it's installed and accessible from your current path by executing \"%s\".\n" % (command[0], command[0]), e.args[0])
234243
else:
235244
raise e
236245

@@ -251,12 +260,12 @@ def pquery(command, output_callback=None, stdin=None, **kwargs):
251260
stdout, _ = proc.communicate(stdin)
252261

253262
if very_verbose:
254-
log(str(stdout).strip()+"\n")
263+
log(stdout.decode("utf-8").strip() + "\n")
255264

256265
if proc.returncode != 0:
257266
raise ProcessException(proc.returncode, command[0], ' '.join(command), getcwd())
258267

259-
return stdout
268+
return stdout.decode("utf-8")
260269

261270
def rmtree_readonly(directory):
262271
if os.path.islink(directory):
@@ -346,15 +355,15 @@ def clone(url, path=None, depth=None, protocol=None):
346355
except Exception as e:
347356
if os.path.isdir(path):
348357
rmtree_readonly(path)
349-
error(e[1], e[0])
358+
error(e.args[1], e.args[0])
350359

351360
def fetch_rev(url, rev):
352361
rev_file = os.path.join('.'+Bld.name, '.rev-' + rev + '.zip')
353362
try:
354363
if not os.path.exists(rev_file):
355364
action("Downloading library build \"%s\" (might take a minute)" % rev)
356365
outfd = open(rev_file, 'wb')
357-
inurl = urllib2.urlopen(url)
366+
inurl = urlopen(url)
358367
outfd.write(inurl.read())
359368
outfd.close()
360369
except:
@@ -393,7 +402,7 @@ def checkout(rev, clean=False):
393402
Bld.unpack_rev(rev)
394403
Bld.seturl(url+'/'+rev)
395404
except Exception as e:
396-
error(e[1], e[0])
405+
error(e.args[1], e.args[0])
397406

398407
def update(rev=None, clean=False, clean_files=False, is_local=False):
399408
return Bld.checkout(rev, clean)
@@ -513,7 +522,7 @@ def outgoing():
513522
pquery([hg_cmd, 'outgoing'])
514523
return 1
515524
except ProcessException as e:
516-
if e[0] != 1:
525+
if e.args[0] != 1:
517526
raise e
518527
return 0
519528

@@ -567,8 +576,9 @@ def geturl():
567576

568577
def getrev():
569578
if os.path.isfile(os.path.join('.hg', 'dirstate')):
579+
from io import open
570580
with open(os.path.join('.hg', 'dirstate'), 'rb') as f:
571-
return ''.join('%02x'%ord(i) for i in f.read(6))
581+
return "".join('{:02x}'.format(x) for x in bytearray(f.read(6)))
572582
else:
573583
return ""
574584

@@ -1282,7 +1292,7 @@ def write(self):
12821292

12831293
ref = url.rstrip('/') + '/' + (('' if self.is_build else '#') + self.rev if self.rev else '')
12841294
action("Updating reference \"%s\" -> \"%s\"" % (relpath(cwd_root, self.path) if cwd_root != self.path else self.name, ref))
1285-
with open(self.lib, 'wb') as f:
1295+
with open(self.lib, 'w') as f:
12861296
f.write(ref+"\n")
12871297

12881298
def rm_untracked(self):
@@ -1295,7 +1305,7 @@ def rm_untracked(self):
12951305
def url2cachedir(self, url):
12961306
up = urlparse(formaturl(url, 'https'))
12971307
if self.cache and up and up.netloc:
1298-
return os.path.join(self.cache, urllib.quote(up.netloc), urllib.quote(re.sub(r'^/', '', up.path)))
1308+
return os.path.join(self.cache, quote(up.netloc), quote(re.sub(r'^/', '', up.path)))
12991309

13001310
def get_cache(self, url, scm):
13011311
cpath = self.url2cachedir(url)
@@ -1992,7 +2002,7 @@ def import_(url, path=None, ignore=False, depth=None, protocol=None, insecure=Fa
19922002
if ignore:
19932003
warning(err)
19942004
else:
1995-
error(err, e[0])
2005+
error(err, e.args[0])
19962006
else:
19972007
err = "Unable to clone repository (%s)" % url
19982008
if ignore:
@@ -2142,7 +2152,7 @@ def publish(all_refs=None, msg=None, top=True):
21422152
if top:
21432153
action("Nothing to publish to the remote repository (the source tree is unmodified)")
21442154
except ProcessException as e:
2145-
if e[0] != 1:
2155+
if e.args[0] != 1:
21462156
raise e
21472157

21482158

@@ -2209,7 +2219,7 @@ def update(rev=None, clean=False, clean_files=False, clean_deps=False, ignore=Fa
22092219
if ignore:
22102220
warning(err)
22112221
else:
2212-
error(err, e[0])
2222+
error(err, e.args[0])
22132223

22142224
repo.rm_untracked()
22152225
if top and cwd_type == 'library':
@@ -2341,7 +2351,7 @@ def sync(recursive=True, keep_refs=False, top=True):
23412351
def list_(detailed=False, prefix='', p_path=None, ignore=False):
23422352
repo = Repo.fromrepo()
23432353

2344-
print "%s (%s)" % (prefix + (relpath(p_path, repo.path) if p_path else repo.name), ((repo.url + ('#' + str(repo.rev)[:12] if repo.rev else '') if detailed else repo.revtype(repo.rev, fmt=6)) or 'no revision'))
2354+
print("%s (%s)" % (prefix + (relpath(p_path, repo.path) if p_path else repo.name), ((repo.url + ('#' + str(repo.rev)[:12] if repo.rev else '') if detailed else repo.revtype(repo.rev, fmt=6)) or 'no revision')))
23452355

23462356
for i, lib in enumerate(sorted(repo.libs, key=lambda l: l.path)):
23472357
nprefix = (prefix[:-3] + ('| ' if prefix[-3] == '|' else ' ')) if prefix else ''
@@ -2374,16 +2384,16 @@ def releases_(detailed=False, unstable=False, recursive=False, prefix='', p_path
23742384
rels.append(tag[1] + " %s%s" % ('#' + tag[0] if detailed else "", " <- current" if tag[1] in revtags else ""))
23752385

23762386
# Print header
2377-
print "%s (%s)" % (prefix + (relpath(p_path, repo.path) if p_path else repo.name), ((repo.url + ('#' + str(repo.rev)[:12] if repo.rev else '') if detailed else repo.revtype(repo.rev, fmt=6)) or 'no revision'))
2387+
print("%s (%s)" % (prefix + (relpath(p_path, repo.path) if p_path else repo.name), ((repo.url + ('#' + str(repo.rev)[:12] if repo.rev else '') if detailed else repo.revtype(repo.rev, fmt=6)) or 'no revision')))
23782388

23792389
# Print list of tags
23802390
rprefix = (prefix[:-3] + ('| ' if prefix[-3] == '|' else ' ')) if recursive and prefix else ''
23812391
rprefix += '| ' if recursive and len(repo.libs) > 1 else ' '
23822392
if len(rels):
23832393
for rel in rels:
2384-
print rprefix + '* ' + rel
2394+
print(rprefix + '* ' + rel)
23852395
else:
2386-
print rprefix + 'No release tags detected'
2396+
print(rprefix + 'No release tags detected')
23872397

23882398
if recursive:
23892399
for i, lib in enumerate(sorted(repo.libs, key=lambda l: l.path)):
@@ -2466,8 +2476,8 @@ def compile_(toolchain=None, target=None, profile=False, compile_library=False,
24662476
# Compile configuration
24672477
popen([python_cmd, os.path.join(tools_dir, 'get_config.py')]
24682478
+ ['-t', tchain, '-m', target]
2469-
+ list(chain.from_iterable(izip(repeat('--profile'), profile or [])))
2470-
+ list(chain.from_iterable(izip(repeat('--source'), source)))
2479+
+ list(chain.from_iterable(zip(repeat('--profile'), profile or [])))
2480+
+ list(chain.from_iterable(zip(repeat('--source'), source)))
24712481
+ (['-v'] if verbose else [])
24722482
+ (list(chain.from_iterable(izip(repeat('--prefix'), config_prefix))) if config_prefix else []),
24732483
env=env)
@@ -2484,10 +2494,10 @@ def compile_(toolchain=None, target=None, profile=False, compile_library=False,
24842494
build_path = os.path.join(os.path.relpath(program.path, orig_path), program.build_dir, 'libraries', os.path.basename(orig_path), target, tchain)
24852495

24862496
popen([python_cmd, '-u', os.path.join(tools_dir, 'build.py')]
2487-
+ list(chain.from_iterable(izip(repeat('-D'), macros)))
2497+
+ list(chain.from_iterable(zip(repeat('-D'), macros)))
24882498
+ ['-t', tchain, '-m', target]
2489-
+ list(chain.from_iterable(izip(repeat('--profile'), profile or [])))
2490-
+ list(chain.from_iterable(izip(repeat('--source'), source)))
2499+
+ list(chain.from_iterable(zip(repeat('--profile'), profile or [])))
2500+
+ list(chain.from_iterable(zip(repeat('--source'), source)))
24912501
+ ['--build', build_path]
24922502
+ (['-c'] if clean else [])
24932503
+ (['--artifact-name', artifact_name] if artifact_name else [])
@@ -2500,10 +2510,10 @@ def compile_(toolchain=None, target=None, profile=False, compile_library=False,
25002510
build_path = os.path.join(os.path.relpath(program.path, orig_path), program.build_dir, target, tchain)
25012511

25022512
popen([python_cmd, '-u', os.path.join(tools_dir, 'make.py')]
2503-
+ list(chain.from_iterable(izip(repeat('-D'), macros)))
2513+
+ list(chain.from_iterable(zip(repeat('-D'), macros)))
25042514
+ ['-t', tchain, '-m', target]
2505-
+ list(chain.from_iterable(izip(repeat('--profile'), profile or [])))
2506-
+ list(chain.from_iterable(izip(repeat('--source'), source)))
2515+
+ list(chain.from_iterable(zip(repeat('--profile'), profile or [])))
2516+
+ list(chain.from_iterable(zip(repeat('--source'), source)))
25072517
+ ['--build', build_path]
25082518
+ (['-c'] if clean else [])
25092519
+ (['--artifact-name', artifact_name] if artifact_name else [])
@@ -2590,9 +2600,9 @@ def test_(toolchain=None, target=None, compile_list=False, run_list=False, compi
25902600

25912601
if compile_list:
25922602
popen([python_cmd, '-u', os.path.join(tools_dir, 'test.py'), '--list']
2593-
+ list(chain.from_iterable(izip(repeat('--profile'), profile or [])))
2603+
+ list(chain.from_iterable(list(izip(repeat('--profile'), profile or []))))
25942604
+ ['-t', tchain, '-m', target]
2595-
+ list(chain.from_iterable(izip(repeat('--source'), source)))
2605+
+ list(chain.from_iterable(zip(repeat('--source'), source)))
25962606
+ (['-n', tests_by_name] if tests_by_name else [])
25972607
+ (['-v'] if verbose else [])
25982608
+ (['--app-config', app_config] if app_config else [])
@@ -2606,11 +2616,11 @@ def test_(toolchain=None, target=None, compile_list=False, run_list=False, compi
26062616
program.ignore_build_dir()
26072617

26082618
popen([python_cmd, '-u', os.path.join(tools_dir, 'test.py')]
2609-
+ list(chain.from_iterable(izip(repeat('-D'), macros)))
2610-
+ list(chain.from_iterable(izip(repeat('--profile'), profile or [])))
2619+
+ list(chain.from_iterable(zip(repeat('-D'), macros)))
2620+
+ list(chain.from_iterable(zip(repeat('--profile'), profile or [])))
26112621
+ ['-t', tchain, '-m', target]
26122622
+ (['-c'] if clean else [])
2613-
+ list(chain.from_iterable(izip(repeat('--source'), source)))
2623+
+ list(chain.from_iterable(zip(repeat('--source'), source)))
26142624
+ ['--build', build_path]
26152625
+ ['--test-spec', test_spec]
26162626
+ (['-n', tests_by_name] if tests_by_name else [])
@@ -2947,7 +2957,7 @@ def get_size_(path):
29472957
action("Repository cache is %s." % str(cfg['cache']).upper())
29482958
action("Cache location \"%s\"" % cfg['cache_dir'])
29492959
else:
2950-
print cmd
2960+
print(cmd)
29512961
error("Invalid cache command. Please see \"mbed cache --help\" for valid commands.")
29522962

29532963

@@ -2963,11 +2973,6 @@ def main():
29632973
# Help messages adapt based on current dir
29642974
cwd_root = getcwd()
29652975

2966-
if sys.version_info[0] != 2 or sys.version_info[1] < 7:
2967-
error(
2968-
"mbed CLI is compatible with Python version >= 2.7 and < 3.0\n"
2969-
"Please refer to the online guide available at https://github.com/ARMmbed/mbed-cli")
2970-
29712976
# Parse/run command
29722977
if len(sys.argv) <= 1:
29732978
help_()
@@ -2988,14 +2993,14 @@ def main():
29882993
except ProcessException as e:
29892994
error(
29902995
"\"%s\" returned error code %d.\n"
2991-
"Command \"%s\" in \"%s\"" % (e[1], e[0], e[2], e[3]), e[0])
2996+
"Command \"%s\" in \"%s\"" % (e.args[1], e.args[0], e.args[2], e.args[3]), e.args[0])
29922997
except OSError as e:
2993-
if e[0] == errno.ENOENT:
2998+
if e.args[0] == errno.ENOENT:
29942999
error(
29953000
"Could not detect one of the command-line tools.\n"
2996-
"You could retry the last command with \"-v\" flag for verbose output\n", e[0])
3001+
"You could retry the last command with \"-v\" flag for verbose output\n", e.args[0])
29973002
else:
2998-
error('OS Error: %s' % e[1], e[0])
3003+
error('OS Error: %s' % e.args[1], e.args[0])
29993004
except KeyboardInterrupt:
30003005
info('User aborted!', -1)
30013006
sys.exit(255)

test/add_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ def test_add(mbed, testrepos):
1717
test3 = testrepos[2]
1818

1919
with cd('test1'):
20-
popen(['python', mbed, 'add', test3])
20+
popen(['python', mbed, 'add', test3, "-vv"])
2121

2222
assertls(mbed, 'test1', [
2323
"test1",
@@ -34,7 +34,7 @@ def test_import_after_add(mbed, testrepos):
3434
mkcommit('test1')
3535

3636
test1 = testrepos[0]
37-
popen(['python', mbed, 'import', test1, 'testimport'])
37+
popen(['python', mbed, 'import', test1, 'testimport', "-vv"])
3838

3939
assertls(mbed, 'testimport', [
4040
"testimport",

0 commit comments

Comments
 (0)