all: Rename "sys" module to "usys".

This is consistent with the other 'micro' modules and allows implementing
additional features in Python via e.g. micropython-lib's sys.

Note this is a breaking change (not backwards compatible) for ports which
do not enable weak links, as "import sys" must now be replaced with
"import usys".
This commit is contained in:
stijn 2020-06-18 11:19:14 +02:00 committed by Damien George
parent b0932fcf2e
commit 40ad8f1666
46 changed files with 142 additions and 89 deletions

View File

@ -77,7 +77,6 @@ it will fallback to loading the built-in ``ujson`` module.
cmath.rst cmath.rst
gc.rst gc.rst
math.rst math.rst
sys.rst
uarray.rst uarray.rst
uasyncio.rst uasyncio.rst
ubinascii.rst ubinascii.rst
@ -93,6 +92,7 @@ it will fallback to loading the built-in ``ujson`` module.
usocket.rst usocket.rst
ussl.rst ussl.rst
ustruct.rst ustruct.rst
usys.rst
utime.rst utime.rst
uzlib.rst uzlib.rst
_thread.rst _thread.rst

View File

@ -1,7 +1,7 @@
:mod:`sys` -- system specific functions :mod:`usys` -- system specific functions
======================================= ========================================
.. module:: sys .. module:: usys
:synopsis: system specific functions :synopsis: system specific functions
|see_cpython_module| :mod:`python:sys`. |see_cpython_module| :mod:`python:sys`.
@ -28,10 +28,10 @@ Functions
This function is a MicroPython extension intended to provide similar This function is a MicroPython extension intended to provide similar
functionality to the :mod:`atexit` module in CPython. functionality to the :mod:`atexit` module in CPython.
.. function:: print_exception(exc, file=sys.stdout, /) .. function:: print_exception(exc, file=usys.stdout, /)
Print exception with a traceback to a file-like object *file* (or Print exception with a traceback to a file-like object *file* (or
`sys.stdout` by default). `usys.stdout` by default).
.. admonition:: Difference to CPython .. admonition:: Difference to CPython
:class: attention :class: attention
@ -84,7 +84,7 @@ Constants
value directly, but instead count number of bits in it:: value directly, but instead count number of bits in it::
bits = 0 bits = 0
v = sys.maxsize v = usys.maxsize
while v: while v:
bits += 1 bits += 1
v >>= 1 v >>= 1
@ -113,7 +113,7 @@ Constants
is an identifier of a board, e.g. ``"pyboard"`` for the original MicroPython is an identifier of a board, e.g. ``"pyboard"`` for the original MicroPython
reference board. It thus can be used to distinguish one board from another. reference board. It thus can be used to distinguish one board from another.
If you need to check whether your program runs on MicroPython (vs other If you need to check whether your program runs on MicroPython (vs other
Python implementation), use `sys.implementation` instead. Python implementation), use `usys.implementation` instead.
.. data:: stderr .. data:: stderr

View File

@ -1,6 +1,6 @@
"""Test for nrf24l01 module. Portable between MicroPython targets.""" """Test for nrf24l01 module. Portable between MicroPython targets."""
import sys import usys
import ustruct as struct import ustruct as struct
import utime import utime
from machine import Pin, SPI from machine import Pin, SPI
@ -14,14 +14,14 @@ _RX_POLL_DELAY = const(15)
# master may be a slow device. Value tested with Pyboard, ESP32 and ESP8266. # master may be a slow device. Value tested with Pyboard, ESP32 and ESP8266.
_SLAVE_SEND_DELAY = const(10) _SLAVE_SEND_DELAY = const(10)
if sys.platform == "pyboard": if usys.platform == "pyboard":
cfg = {"spi": 2, "miso": "Y7", "mosi": "Y8", "sck": "Y6", "csn": "Y5", "ce": "Y4"} cfg = {"spi": 2, "miso": "Y7", "mosi": "Y8", "sck": "Y6", "csn": "Y5", "ce": "Y4"}
elif sys.platform == "esp8266": # Hardware SPI elif usys.platform == "esp8266": # Hardware SPI
cfg = {"spi": 1, "miso": 12, "mosi": 13, "sck": 14, "csn": 4, "ce": 5} cfg = {"spi": 1, "miso": 12, "mosi": 13, "sck": 14, "csn": 4, "ce": 5}
elif sys.platform == "esp32": # Software SPI elif usys.platform == "esp32": # Software SPI
cfg = {"spi": -1, "miso": 32, "mosi": 33, "sck": 25, "csn": 26, "ce": 27} cfg = {"spi": -1, "miso": 32, "mosi": 33, "sck": 25, "csn": 26, "ce": 27}
else: else:
raise ValueError("Unsupported platform {}".format(sys.platform)) raise ValueError("Unsupported platform {}".format(usys.platform))
# Addresses are in little-endian format. They correspond to big-endian # Addresses are in little-endian format. They correspond to big-endian
# 0xf0f0f0f0e1, 0xf0f0f0f0d2 # 0xf0f0f0f0e1, 0xf0f0f0f0d2

View File

@ -1,4 +1,7 @@
import sys try:
import usys as sys
except ImportError:
import sys
try: try:
import ubinascii as binascii import ubinascii as binascii

View File

@ -159,7 +159,7 @@ STATIC const mp_rom_map_elem_t mp_builtin_module_table[] = {
#endif #endif
#endif #endif
#if MICROPY_PY_SYS #if MICROPY_PY_SYS
{ MP_ROM_QSTR(MP_QSTR_sys), MP_ROM_PTR(&mp_module_sys) }, { MP_ROM_QSTR(MP_QSTR_usys), MP_ROM_PTR(&mp_module_sys) },
#endif #endif
#if MICROPY_PY_GC && MICROPY_ENABLE_GC #if MICROPY_PY_GC && MICROPY_ENABLE_GC
{ MP_ROM_QSTR(MP_QSTR_gc), MP_ROM_PTR(&mp_module_gc) }, { MP_ROM_QSTR(MP_QSTR_gc), MP_ROM_PTR(&mp_module_gc) },

View File

@ -1,6 +1,9 @@
# test await expression # test await expression
import sys try:
import usys as sys
except ImportError:
import sys
if sys.implementation.name == 'micropython': if sys.implementation.name == 'micropython':
# uPy allows normal generators to be awaitables # uPy allows normal generators to be awaitables
coroutine = lambda f: f coroutine = lambda f: f

View File

@ -1,6 +1,9 @@
# test waiting within "async for" __anext__ function # test waiting within "async for" __anext__ function
import sys try:
import usys as sys
except ImportError:
import sys
if sys.implementation.name == 'micropython': if sys.implementation.name == 'micropython':
# uPy allows normal generators to be awaitables # uPy allows normal generators to be awaitables
coroutine = lambda f: f coroutine = lambda f: f

View File

@ -1,6 +1,9 @@
# test waiting within async with enter/exit functions # test waiting within async with enter/exit functions
import sys try:
import usys as sys
except ImportError:
import sys
if sys.implementation.name == 'micropython': if sys.implementation.name == 'micropython':
# uPy allows normal generators to be awaitables # uPy allows normal generators to be awaitables
coroutine = lambda f: f coroutine = lambda f: f

View File

@ -1,7 +1,10 @@
# test attrtuple # test attrtuple
# we can't test this type directly so we use sys.implementation object # we can't test this type directly so we use sys.implementation object
import sys try:
import usys as sys
except ImportError:
import sys
t = sys.implementation t = sys.implementation
# It can be just a normal tuple on small ports # It can be just a normal tuple on small ports

View File

@ -7,7 +7,10 @@ print(callable([]))
print(callable("dfsd")) print(callable("dfsd"))
# modules should not be callabe # modules should not be callabe
import sys try:
import usys as sys
except ImportError:
import sys
print(callable(sys)) print(callable(sys))
# builtins should be callable # builtins should be callable

View File

@ -4,7 +4,10 @@
print('__name__' in dir()) print('__name__' in dir())
# dir of module # dir of module
import sys try:
import usys as sys
except ImportError:
import sys
print('version' in dir(sys)) print('version' in dir(sys))
# dir of type # dir of type

View File

@ -102,7 +102,10 @@ x = 4611686018427387904 # big
x = -4611686018427387904 # big x = -4611686018427387904 # big
# sys.maxsize is a constant mpz, so test it's compatible with dynamic ones # sys.maxsize is a constant mpz, so test it's compatible with dynamic ones
import sys try:
import usys as sys
except ImportError:
import sys
print(sys.maxsize + 1 - 1 == sys.maxsize) print(sys.maxsize + 1 - 1 == sys.maxsize)
# test extraction of big int value via mp_obj_get_int_maybe # test extraction of big int value via mp_obj_get_int_maybe

View File

@ -1,6 +1,6 @@
# uPy behaviour only: builtin modules are read-only # uPy behaviour only: builtin modules are read-only
import sys import usys
try: try:
sys.x = 1 usys.x = 1
except AttributeError: except AttributeError:
print("AttributeError") print("AttributeError")

View File

@ -33,9 +33,9 @@ test_syntax("del ()") # can't delete empty tuple (in 3.6 we can)
# from basics/sys1.py # from basics/sys1.py
# uPy prints version 3.4 # uPy prints version 3.4
import sys import usys
print(sys.version[:3]) print(usys.version[:3])
print(sys.version_info[0], sys.version_info[1]) print(usys.version_info[0], usys.version_info[1])
# from basics/exception1.py # from basics/exception1.py
# in 3.7 no comma is printed if there is only 1 arg (in 3.4-3.6 one is printed) # in 3.7 no comma is printed if there is only 1 arg (in 3.4-3.6 one is printed)

View File

@ -51,7 +51,10 @@ print("1/" <= "1")
# this tests an internal string that doesn't have a hash with a string # this tests an internal string that doesn't have a hash with a string
# that does have a hash, but the lengths of the two strings are different # that does have a hash, but the lengths of the two strings are different
import sys try:
import usys as sys
except ImportError:
import sys
print(sys.version == 'a long string that has a hash') print(sys.version == 'a long string that has a hash')
# this special string would have a hash of 0 but is incremented to 1 # this special string would have a hash of 0 but is incremented to 1

View File

@ -1,6 +1,9 @@
# test sys module # test sys module
import sys try:
import usys as sys
except ImportError:
import sys
print(sys.__name__) print(sys.__name__)
print(type(sys.path)) print(type(sys.path))

View File

@ -1,6 +1,9 @@
# test sys module's exit function # test sys module's exit function
import sys try:
import usys as sys
except ImportError:
import sys
try: try:
sys.exit sys.exit

View File

@ -1,6 +1,9 @@
# test sys.getsizeof() function # test sys.getsizeof() function
import sys try:
import usys as sys
except ImportError:
import sys
try: try:
sys.getsizeof sys.getsizeof
except AttributeError: except AttributeError:

View File

@ -1,4 +1,4 @@
import sys import usys
try: try:
import uctypes import uctypes
@ -6,7 +6,7 @@ except ImportError:
print("SKIP") print("SKIP")
raise SystemExit raise SystemExit
if sys.byteorder != "little": if usys.byteorder != "little":
print("SKIP") print("SKIP")
raise SystemExit raise SystemExit

View File

@ -1,4 +1,4 @@
import sys import usys
try: try:
import uctypes import uctypes
@ -6,7 +6,7 @@ except ImportError:
print("SKIP") print("SKIP")
raise SystemExit raise SystemExit
if sys.byteorder != "little": if usys.byteorder != "little":
print("SKIP") print("SKIP")
raise SystemExit raise SystemExit

View File

@ -1,7 +1,7 @@
# This test is exactly like uctypes_le.py, but uses native structure layout. # This test is exactly like uctypes_le.py, but uses native structure layout.
# Codepaths for packed vs native structures are different. This test only works # Codepaths for packed vs native structures are different. This test only works
# on little-endian machine (no matter if 32 or 64 bit). # on little-endian machine (no matter if 32 or 64 bit).
import sys import usys
try: try:
import uctypes import uctypes
@ -9,7 +9,7 @@ except ImportError:
print("SKIP") print("SKIP")
raise SystemExit raise SystemExit
if sys.byteorder != "little": if usys.byteorder != "little":
print("SKIP") print("SKIP")
raise SystemExit raise SystemExit

View File

@ -1,4 +1,4 @@
import sys import usys
try: try:
import uctypes import uctypes
@ -6,7 +6,7 @@ except ImportError:
print("SKIP") print("SKIP")
raise SystemExit raise SystemExit
if sys.byteorder != "little": if usys.byteorder != "little":
print("SKIP") print("SKIP")
raise SystemExit raise SystemExit

View File

@ -1,4 +1,4 @@
import sys import usys
try: try:
import uctypes import uctypes
@ -6,7 +6,7 @@ except ImportError:
print("SKIP") print("SKIP")
raise SystemExit raise SystemExit
if sys.byteorder != "little": if usys.byteorder != "little":
print("SKIP") print("SKIP")
raise SystemExit raise SystemExit

View File

@ -111,10 +111,10 @@ print(uos.listdir())
print(uos.listdir("sys")) print(uos.listdir("sys"))
# test importing a file from a mounted FS # test importing a file from a mounted FS
import sys import usys
sys.path.clear() usys.path.clear()
sys.path.append("/sys") usys.path.append("/sys")
with open("sys/test_module.py", "w") as f: with open("sys/test_module.py", "w") as f:
f.write('print("test_module!")') f.write('print("test_module!")')
import test_module import test_module

View File

@ -68,17 +68,17 @@ def test(bdev, vfs_class):
uos.umount("/lfs") uos.umount("/lfs")
# clear imported modules # clear imported modules
sys.modules.clear() usys.modules.clear()
bdev = RAMBlockDevice(30) bdev = RAMBlockDevice(30)
# initialise path # initialise path
import sys import usys
sys.path.clear() usys.path.clear()
sys.path.append("/lfs") usys.path.append("/lfs")
sys.path.append("") usys.path.append("")
# run tests # run tests
test(bdev, uos.VfsLfs1) test(bdev, uos.VfsLfs1)

View File

@ -1,7 +1,7 @@
# test VFS functionality with a user-defined filesystem # test VFS functionality with a user-defined filesystem
# also tests parts of uio.IOBase implementation # also tests parts of uio.IOBase implementation
import sys import usys
try: try:
import uio import uio
@ -76,9 +76,9 @@ f = open("/userfs/data.txt")
print(f.read()) print(f.read())
# import files from the user filesystem # import files from the user filesystem
sys.path.append("/userfs") usys.path.append("/userfs")
import usermod1 import usermod1
# unmount and undo path addition # unmount and undo path addition
uos.umount("/userfs") uos.umount("/userfs")
sys.path.pop() usys.path.pop()

View File

@ -1,3 +1,6 @@
import sys try:
import usys as sys
except ImportError:
import sys
print(sys.byteorder) print(sys.byteorder)

View File

@ -2,10 +2,10 @@
try: try:
import ustruct as struct import ustruct as struct
import usys as sys
except: except:
import struct import struct
import sys
import sys
maxsize_bits = 0 maxsize_bits = 0
maxsize = sys.maxsize maxsize = sys.maxsize

View File

@ -2,10 +2,10 @@
try: try:
import ustruct as struct import ustruct as struct
import usys as sys
except: except:
import struct import struct
import sys
import sys
maxsize_bits = 0 maxsize_bits = 0
maxsize = sys.maxsize maxsize = sys.maxsize

View File

@ -2,10 +2,10 @@
try: try:
import ustruct as struct import ustruct as struct
import usys as sys
except: except:
import struct import struct
import sys
import sys
maxsize_bits = 0 maxsize_bits = 0
maxsize = sys.maxsize maxsize = sys.maxsize

View File

@ -1,3 +1,6 @@
import sys try:
import usys as sys
except ImportError:
import sys
print(sys.argv) print(sys.argv)

View File

@ -1,6 +1,9 @@
# test builtin print function, using file= argument # test builtin print function, using file= argument
import sys try:
import usys as sys
except ImportError:
import sys
try: try:
sys.stdout sys.stdout

View File

@ -1,4 +1,7 @@
import sys try:
import usys as sys
except ImportError:
import sys
print(sys.stdin.fileno()) print(sys.stdin.fileno())
print(sys.stdout.fileno()) print(sys.stdout.fileno())

View File

@ -1,5 +1,5 @@
import uio import uio
import sys import usys
try: try:
uio.resource_stream uio.resource_stream
@ -11,5 +11,5 @@ buf = uio.resource_stream("data", "file2")
print(buf.read()) print(buf.read())
# resource_stream(None, ...) look ups from current dir, hence sys.path[0] hack # resource_stream(None, ...) look ups from current dir, hence sys.path[0] hack
buf = uio.resource_stream(None, sys.path[0] + "/data/file2") buf = uio.resource_stream(None, usys.path[0] + "/data/file2")
print(buf.read()) print(buf.read())

View File

@ -1,7 +1,7 @@
# test that emergency exceptions work # test that emergency exceptions work
import micropython import micropython
import sys import usys
try: try:
import uio import uio
@ -26,7 +26,7 @@ def f():
# print the exception # print the exception
buf = uio.StringIO() buf = uio.StringIO()
sys.print_exception(exc, buf) usys.print_exception(exc, buf)
for l in buf.getvalue().split("\n"): for l in buf.getvalue().split("\n"):
if l.startswith(" File "): if l.startswith(" File "):
print(l.split('"')[2]) print(l.split('"')[2])

View File

@ -1,7 +1,7 @@
# test that we can generate a traceback without allocating # test that we can generate a traceback without allocating
import micropython import micropython
import sys import usys
try: try:
import uio import uio
@ -33,7 +33,7 @@ test()
# print the exception that was raised # print the exception that was raised
buf = uio.StringIO() buf = uio.StringIO()
sys.print_exception(global_exc, buf) usys.print_exception(global_exc, buf)
for l in buf.getvalue().split("\n"): for l in buf.getvalue().split("\n"):
# uPy on pyboard prints <stdin> as file, so remove filename. # uPy on pyboard prints <stdin> as file, so remove filename.
if l.startswith(" File "): if l.startswith(" File "):

View File

@ -1,7 +1,7 @@
# test importing of invalid .mpy files # test importing of invalid .mpy files
try: try:
import sys, uio, uos import usys, uio, uos
uio.IOBase uio.IOBase
uos.mount uos.mount
@ -54,7 +54,7 @@ user_files = {
# create and mount a user filesystem # create and mount a user filesystem
uos.mount(UserFS(user_files), "/userfs") uos.mount(UserFS(user_files), "/userfs")
sys.path.append("/userfs") usys.path.append("/userfs")
# import .mpy files from the user filesystem # import .mpy files from the user filesystem
for i in range(len(user_files)): for i in range(len(user_files)):
@ -66,4 +66,4 @@ for i in range(len(user_files)):
# unmount and undo path addition # unmount and undo path addition
uos.umount("/userfs") uos.umount("/userfs")
sys.path.pop() usys.path.pop()

View File

@ -1,7 +1,7 @@
# test importing of .mpy files with native code (x64 only) # test importing of .mpy files with native code (x64 only)
try: try:
import sys, uio, uos import usys, uio, uos
uio.IOBase uio.IOBase
uos.mount uos.mount
@ -9,7 +9,7 @@ except (ImportError, AttributeError):
print("SKIP") print("SKIP")
raise SystemExit raise SystemExit
if not (sys.platform == "linux" and sys.maxsize > 2 ** 32): if not (usys.platform == "linux" and usys.maxsize > 2 ** 32):
print("SKIP") print("SKIP")
raise SystemExit raise SystemExit
@ -101,7 +101,7 @@ user_files = {
# create and mount a user filesystem # create and mount a user filesystem
uos.mount(UserFS(user_files), "/userfs") uos.mount(UserFS(user_files), "/userfs")
sys.path.append("/userfs") usys.path.append("/userfs")
# import .mpy files from the user filesystem # import .mpy files from the user filesystem
for i in range(len(user_files)): for i in range(len(user_files)):
@ -114,4 +114,4 @@ for i in range(len(user_files)):
# unmount and undo path addition # unmount and undo path addition
uos.umount("/userfs") uos.umount("/userfs")
sys.path.pop() usys.path.pop()

View File

@ -3,4 +3,4 @@ import micropython as micropython
# check that level 3 doesn't store line numbers # check that level 3 doesn't store line numbers
# the expected output is that any line is printed as "line 1" # the expected output is that any line is printed as "line 1"
micropython.opt_level(3) micropython.opt_level(3)
exec("try:\n xyz\nexcept NameError as er:\n import sys\n sys.print_exception(er)") exec("try:\n xyz\nexcept NameError as er:\n import usys\n usys.print_exception(er)")

View File

@ -6,6 +6,6 @@ def viper_uint() -> uint:
return uint(-1) return uint(-1)
import sys import usys
print(viper_uint() == (sys.maxsize << 1 | 1)) print(viper_uint() == (usys.maxsize << 1 | 1))

View File

@ -1,10 +1,10 @@
import sys
try: try:
try: try:
import uio as io import uio as io
import usys as sys
except ImportError: except ImportError:
import io import io
import sys
except ImportError: except ImportError:
print("SKIP") print("SKIP")
raise SystemExit raise SystemExit

View File

@ -1,9 +1,9 @@
# test sys.atexit() function # test sys.atexit() function
import sys import usys
try: try:
sys.atexit usys.atexit
except AttributeError: except AttributeError:
print("SKIP") print("SKIP")
raise SystemExit raise SystemExit
@ -15,7 +15,7 @@ def do_at_exit():
print("done at exit:", some_var) print("done at exit:", some_var)
sys.atexit(do_at_exit) usys.atexit(do_at_exit)
some_var = "ok" some_var = "ok"
print("done before exit") print("done before exit")

View File

@ -1,4 +1,7 @@
import sys try:
import usys as sys
except ImportError:
import sys
try: try:
sys.exc_info sys.exc_info

View File

@ -30,7 +30,7 @@ TEST_MAPPINGS = {
# Code to allow a target MicroPython to import an .mpy from RAM # Code to allow a target MicroPython to import an .mpy from RAM
injected_import_hook_code = """\ injected_import_hook_code = """\
import sys, uos, uio import usys, uos, uio
class __File(uio.IOBase): class __File(uio.IOBase):
def __init__(self): def __init__(self):
self.off = 0 self.off = 0
@ -54,7 +54,7 @@ class __FS:
return __File() return __File()
uos.mount(__FS(), '/__remote') uos.mount(__FS(), '/__remote')
uos.chdir('/__remote') uos.chdir('/__remote')
sys.modules['{}'] = __import__('__injected') usys.modules['{}'] = __import__('__injected')
""" """

View File

@ -5,7 +5,7 @@
# This script is intended to be run by the same interpreter executable # This script is intended to be run by the same interpreter executable
# which is to be tested, so should use minimal language functionality. # which is to be tested, so should use minimal language functionality.
# #
import sys import usys as sys
import uos as os import uos as os

View File

@ -1,8 +1,10 @@
# test setting the thread stack size # test setting the thread stack size
# #
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
try:
import sys import usys as sys
except ImportError:
import sys
import _thread import _thread
# different implementations have different minimum sizes # different implementations have different minimum sizes