diff --git a/LICENSE b/LICENSE index 87095e296..0e9e41d35 100644 --- a/LICENSE +++ b/LICENSE @@ -1,8 +1,8 @@ micropython-lib consists of multiple modules from different sources and -authors. Each module comes under its own licensing terms. Short name of -a license can be found in a file within a module directory (usually -metadata.txt or setup.py). Complete text of each license used is provided -below. Files not belonging to a particular module a provided under MIT +authors. Each module comes under its own licensing terms. The short name of +a license can be found in a file within the module directory (usually +metadata.txt or setup.py). The complete text of each license used is provided +below. Files not belonging to a particular module are provided under the MIT license, unless explicitly stated otherwise. =============== MIT License =============== diff --git a/Makefile b/Makefile deleted file mode 100644 index 7ae088359..000000000 --- a/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -PREFIX = ~/.micropython/lib - -all: - -# Installs all modules to a lib location, for development testing -CMD="find . -maxdepth 1 -mindepth 1 \( -name '*.py' -not -name 'test_*' -not -name 'setup.py' \) -or \( -type d -not -name 'dist' -not -name '*.egg-info' -not -name '__pycache__' \)| xargs --no-run-if-empty cp -r -t $(PREFIX)" -install: - @mkdir -p $(PREFIX) - @if [ -n "$(MOD)" ]; then \ - (cd $(MOD); sh -c $(CMD)); \ - else \ - for d in $$(find -maxdepth 1 -type d ! -name ".*"); do \ - echo $$d; \ - (cd $$d; sh -c $(CMD)); \ - done \ - fi diff --git a/README.md b/README.md index 88d00caba..b5d1b8a46 100644 --- a/README.md +++ b/README.md @@ -1,73 +1,33 @@ micropython-lib =============== -micropython-lib is a project to develop a non-monolothic standard library -for "advanced" MicroPython fork (https://github.com/pfalcon/micropython). -Each module or package is available as a separate distribution package from -PyPI. Each module comes from one of the following sources (and thus each -module has its own licensing terms): -* written from scratch specifically for MicroPython -* ported from CPython -* ported from some other Python implementation, e.g. PyPy -* some modules actually aren't implemented yet and are dummy +This is a repository of libraries designed to be useful for writing +MicroPython applications. -Note that the main target of micropython-lib is a "Unix" port of the -aforementioned fork of MicroPython. Actual system requirements vary per -module. Majority of modules are compatible with the upstream MicroPython, -though some may require additional functionality/optimizations present in -the "advanced" fork. Modules not related to I/O may also work without -problems on bare-metal ports, not just on "Unix" port (e.g. pyboard). +The libraries here fall into four categories corresponding to the four top-level directories: + * **python-stdlib**: Compatible versions of modules from the [Python Standard Library](https://docs.python.org/3/library/). These should be drop-in replacements for the Python libraries, although many have reduced functionality or missing methods or classes (which may not be an issue for many most cases). -Usage ------ -micropython-lib packages are published on PyPI (Python Package Index), -the standard Python community package repository: https://pypi.org/ . -On PyPI, you can search for MicroPython related packages and read -additional package information. By convention, all micropython-lib package -names are prefixed with "micropython-" (the reverse is not true - some -package starting with "micropython-" aren't part of micropython-lib and -were released by 3rd parties). - -Browse available packages [via this -URL](https://pypi.org/search/?q=&o=&c=Programming+Language+%3A%3A+Python+%3A%3A+Implementation+%3A%3A+MicroPython). - -To install packages from PyPI for usage on your local system, use the -`upip` tool, which is MicroPython's native package manager, similar to -`pip`, which is used to install packages for CPython. `upip` is bundled -with MicroPython "Unix" port (i.e. if you build "Unix" port, you -automatically have `upip` tool). Following examples assume that -`micropython` binary is available on your `PATH`: - -~~~~ -$ micropython -m upip install micropython-pystone -... -$ micropython ->>> import pystone ->>> pystone.main() -Pystone(1.2) time for 50000 passes = 0.534 -This machine benchmarks at 93633 pystones/second -~~~~ + * **python-ecosys**: Compatible, but reduced-functionality versions of modules from the larger Python ecosystem, for example that might be found in the [Python Package Index](https://pypi.org/). -Run `micropython -m upip --help` for more information about `upip`. +* **micropython**: MicroPython-specific modules that do not have equivalents in other Python environments. These are typically hardware drivers or highly-optimised alternative implementations of functionality available in other Python modules. + * **unix-ffi**: These modules are specifically for the MicroPython Unix port and provide access to operating-system and third-party libraries via FFI. -Development ------------ -To install modules during development, use `make install`. By default, all -available packages will be installed. To install a specific module, add the -`MOD=` parameter to the end of the `make install` command. - - -Links +Usage ----- -If you would like to trace evolution of MicroPython packaging support, -you may find following links useful (note that they may contain outdated -information): - * https://github.com/micropython/micropython/issues/405 - * http://forum.micropython.org/viewtopic.php?f=5&t=70 +Many libraries are self contained modules, and you can quickly get started by +copying the relevant Python file to your device. For example, to add the +`base64` library, you can directly copy `python-stdlib/base64/base64.py` to the `lib` +directory on your device. + +Other libraries are packages, in which case you'll need to copy the directory instead. For example, to add `collections.defaultdict`, copy `collections/collections/__init__.py` and `collections.defaultdict/collections/defaultdict.py` to a directory named `lib/collections` on your device. -Guidelines for packaging MicroPython modules for PyPI: +Future plans (and new contributor ideas) +---------------------------------------- - * https://github.com/micropython/micropython/issues/413 +* Provide compiled .mpy distributions. +* Develop a set of example programs using these libraries. +* Develop more MicroPython libraries for common tasks. +* Provide a replacement for the previous `upip` tool. diff --git a/__future__/setup.py b/__future__/setup.py deleted file mode 100644 index 9dbd7ef17..000000000 --- a/__future__/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-future', - version='0.0.3', - description='Dummy __future__ module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['__future__']) diff --git a/_libc/setup.py b/_libc/setup.py deleted file mode 100644 index b1dfe1dab..000000000 --- a/_libc/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-libc', - version='0.3.1', - description='MicroPython FFI helper module (deprecated)', - long_description='MicroPython FFI helper module (deprecated, replaced by micropython-ffilib).', - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['_libc']) diff --git a/_markupbase/setup.py b/_markupbase/setup.py deleted file mode 100644 index 341be270c..000000000 --- a/_markupbase/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-_markupbase', - version='3.3.3-1', - description='CPython _markupbase module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['_markupbase'], - install_requires=['micropython-re-pcre']) diff --git a/abc/setup.py b/abc/setup.py deleted file mode 100644 index 9d21d7e87..000000000 --- a/abc/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-abc', - version='0.0.1', - description='Dummy abc module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['abc']) diff --git a/argparse/setup.py b/argparse/setup.py deleted file mode 100644 index f1406147b..000000000 --- a/argparse/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-argparse', - version='0.4', - description='argparse module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Damien George', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['argparse']) diff --git a/array/metadata.txt b/array/metadata.txt deleted file mode 100644 index 976088c8a..000000000 --- a/array/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.0 diff --git a/array/setup.py b/array/setup.py deleted file mode 100644 index 5dcb7e927..000000000 --- a/array/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-array', - version='0.0.0', - description='Dummy array module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['array']) diff --git a/asyncio/metadata.txt b/asyncio/metadata.txt deleted file mode 100644 index 976088c8a..000000000 --- a/asyncio/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.0 diff --git a/asyncio/setup.py b/asyncio/setup.py deleted file mode 100644 index 3fbbde434..000000000 --- a/asyncio/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-asyncio', - version='0.0.0', - description='Dummy asyncio module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['asyncio']) diff --git a/asyncio_slow/asyncio_slow.py b/asyncio_slow/asyncio_slow.py deleted file mode 100644 index 89245ce05..000000000 --- a/asyncio_slow/asyncio_slow.py +++ /dev/null @@ -1,151 +0,0 @@ -import time -import logging - - -log = logging.getLogger("asyncio") - - -# Workaround for not being able to subclass builtin types -class LoopStop(Exception): - pass - -class InvalidStateError(Exception): - pass - -# Object not matching any other object -_sentinel = [] - - -class EventLoop: - - def __init__(self): - self.q = [] - - def call_soon(self, c, *args): - self.q.append((c, args)) - - def call_later(self, delay, c, *args): - def _delayed(c, args, delay): - yield from sleep(delay) - self.call_soon(c, *args) - Task(_delayed(c, args, delay)) - - def run_forever(self): - while self.q: - c = self.q.pop(0) - try: - c[0](*c[1]) - except LoopStop: - return - # I mean, forever - while True: - time.sleep(1) - - def stop(self): - def _cb(): - raise LoopStop - self.call_soon(_cb) - - def run_until_complete(self, coro): - t = ensure_future(coro) - t.add_done_callback(lambda a: self.stop()) - self.run_forever() - - def close(self): - pass - - -_def_event_loop = EventLoop() - - -class Future: - - def __init__(self, loop=_def_event_loop): - self.loop = loop - self.res = _sentinel - self.cbs = [] - - def result(self): - if self.res is _sentinel: - raise InvalidStateError - return self.res - - def add_done_callback(self, fn): - if self.res is _sentinel: - self.cbs.append(fn) - else: - self.loop.call_soon(fn, self) - - def set_result(self, val): - self.res = val - for f in self.cbs: - f(self) - - -class Task(Future): - - def __init__(self, coro, loop=_def_event_loop): - super().__init__() - self.loop = loop - self.c = coro - # upstream asyncio forces task to be scheduled on instantiation - self.loop.call_soon(self) - - def __call__(self): - try: - next(self.c) - self.loop.call_soon(self) - except StopIteration as e: - log.debug("Coro finished: %s", self.c) - self.set_result(None) - - -def get_event_loop(): - return _def_event_loop - - -# Decorator -def coroutine(f): - return f - - -def ensure_future(coro): - if isinstance(coro, Future): - return coro - return Task(coro) - - -class _Wait(Future): - - def __init__(self, n): - Future.__init__(self) - self.n = n - - def _done(self): - self.n -= 1 - log.debug("Wait: remaining tasks: %d", self.n) - if not self.n: - self.set_result(None) - - def __call__(self): - pass - - -def wait(coro_list, loop=_def_event_loop): - - w = _Wait(len(coro_list)) - - for c in coro_list: - t = ensure_future(c) - t.add_done_callback(lambda val: w._done()) - - return w - - -def sleep(secs): - t = time.time() - log.debug("Started sleep at: %s, targetting: %s", t, t + secs) - while time.time() < t + secs: - time.sleep(0.01) - yield - log.debug("Finished sleeping %ss", secs) diff --git a/asyncio_slow/example_chain.py b/asyncio_slow/example_chain.py deleted file mode 100644 index 8d6b9a615..000000000 --- a/asyncio_slow/example_chain.py +++ /dev/null @@ -1,18 +0,0 @@ -#https://docs.python.org/3.4/library/asyncio-task.html#example-chain-coroutines -#import asyncio -import asyncio_slow as asyncio - -@asyncio.coroutine -def compute(x, y): - print("Compute %s + %s ..." % (x, y)) - yield from asyncio.sleep(1.0) - return x + y - -@asyncio.coroutine -def print_sum(x, y): - result = yield from compute(x, y) - print("%s + %s = %s" % (x, y, result)) - -loop = asyncio.get_event_loop() -loop.run_until_complete(print_sum(1, 2)) -loop.close() diff --git a/asyncio_slow/example_future.py b/asyncio_slow/example_future.py deleted file mode 100644 index 53026c8d0..000000000 --- a/asyncio_slow/example_future.py +++ /dev/null @@ -1,15 +0,0 @@ -#https://docs.python.org/3.4/library/asyncio-task.html#example-chain-coroutines -#import asyncio -import asyncio_slow as asyncio - -@asyncio.coroutine -def slow_operation(future): - yield from asyncio.sleep(1) - future.set_result('Future is done!') - -loop = asyncio.get_event_loop() -future = asyncio.Future() -asyncio.Task(slow_operation(future)) -loop.run_until_complete(future) -print(future.result()) -loop.close() diff --git a/asyncio_slow/example_future2.py b/asyncio_slow/example_future2.py deleted file mode 100644 index 8ba03ef85..000000000 --- a/asyncio_slow/example_future2.py +++ /dev/null @@ -1,21 +0,0 @@ -#https://docs.python.org/3.4/library/asyncio-task.html#example-future-with-run-forever -#import asyncio -import asyncio_slow as asyncio - -@asyncio.coroutine -def slow_operation(future): - yield from asyncio.sleep(1) - future.set_result('Future is done!') - -def got_result(future): - print(future.result()) - loop.stop() - -loop = asyncio.get_event_loop() -future = asyncio.Future() -asyncio.Task(slow_operation(future)) -future.add_done_callback(got_result) -try: - loop.run_forever() -finally: - loop.close() \ No newline at end of file diff --git a/asyncio_slow/example_hello_world.py b/asyncio_slow/example_hello_world.py deleted file mode 100644 index fab558134..000000000 --- a/asyncio_slow/example_hello_world.py +++ /dev/null @@ -1,12 +0,0 @@ -#https://docs.python.org/3.4/library/asyncio-task.html#example-hello-world-coroutine -#import asyncio -import asyncio_slow as asyncio - -@asyncio.coroutine -def greet_every_two_seconds(): - while True: - print('Hello World') - yield from asyncio.sleep(2) - -loop = asyncio.get_event_loop() -loop.run_until_complete(greet_every_two_seconds()) diff --git a/asyncio_slow/example_hello_world_bare.py b/asyncio_slow/example_hello_world_bare.py deleted file mode 100644 index 1f8d9702f..000000000 --- a/asyncio_slow/example_hello_world_bare.py +++ /dev/null @@ -1,12 +0,0 @@ -#import asyncio -import asyncio_slow as asyncio - -@asyncio.coroutine -def greet_every_two_seconds(): - while True: - print('Hello World') - yield from asyncio.sleep(2) - -loop = asyncio.get_event_loop() -asyncio.Task(greet_every_two_seconds()) -loop.run_forever() diff --git a/asyncio_slow/example_hello_world_callback.py b/asyncio_slow/example_hello_world_callback.py deleted file mode 100644 index 9836ffd7b..000000000 --- a/asyncio_slow/example_hello_world_callback.py +++ /dev/null @@ -1,11 +0,0 @@ -# https://docs.python.org/3.4/library/asyncio-eventloop.html#example-hello-world-callback -#import asyncio -import asyncio_slow as asyncio - -def print_and_repeat(loop): - print('Hello World') - loop.call_later(2, print_and_repeat, loop) - -loop = asyncio.get_event_loop() -loop.call_soon(print_and_repeat, loop) -loop.run_forever() diff --git a/asyncio_slow/example_parallel.py b/asyncio_slow/example_parallel.py deleted file mode 100644 index 48a187b87..000000000 --- a/asyncio_slow/example_parallel.py +++ /dev/null @@ -1,21 +0,0 @@ -#https://docs.python.org/3.4/library/asyncio-task.html#example-parallel-execution-of-tasks -#import asyncio -import asyncio_slow as asyncio - -@asyncio.coroutine -def factorial(name, number): - f = 1 - for i in range(2, number+1): - print("Task %s: Compute factorial(%s)..." % (name, i)) - yield from asyncio.sleep(1) - f *= i - print("Task %s: factorial(%s) = %s" % (name, number, f)) - -tasks = [ - asyncio.Task(factorial("A", 2)), - asyncio.Task(factorial("B", 3)), - asyncio.Task(factorial("C", 4))] - -loop = asyncio.get_event_loop() -loop.run_until_complete(asyncio.wait(tasks)) -loop.close() diff --git a/base64/setup.py b/base64/setup.py deleted file mode 100644 index 0b3b16e8d..000000000 --- a/base64/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-base64', - version='3.3.3-4', - description='CPython base64 module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['base64'], - install_requires=['micropython-binascii', 'micropython-re-pcre', 'micropython-struct']) diff --git a/binascii/binascii.py b/binascii/binascii.py deleted file mode 100644 index dd6744c2f..000000000 --- a/binascii/binascii.py +++ /dev/null @@ -1,113 +0,0 @@ -from ubinascii import * - -if not "unhexlify" in globals(): - def unhexlify(data): - if len(data) % 2 != 0: - raise ValueError("Odd-length string") - - return bytes([ int(data[i:i+2], 16) for i in range(0, len(data), 2) ]) - -b2a_hex = hexlify -a2b_hex = unhexlify - -# ____________________________________________________________ - -PAD = '=' - -table_a2b_base64 = [ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, # Note PAD->-1 here - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -] -def _transform(n): - if n == -1: - return '\xff' - else: - return chr(n) -table_a2b_base64 = ''.join(map(_transform, table_a2b_base64)) -assert len(table_a2b_base64) == 256 - -def a2b_base64(ascii): - "Decode a line of base64 data." - - res = [] - quad_pos = 0 - leftchar = 0 - leftbits = 0 - last_char_was_a_pad = False - - for c in ascii: - c = chr(c) - if c == PAD: - if quad_pos > 2 or (quad_pos == 2 and last_char_was_a_pad): - break # stop on 'xxx=' or on 'xx==' - last_char_was_a_pad = True - else: - n = ord(table_a2b_base64[ord(c)]) - if n == 0xff: - continue # ignore strange characters - # - # Shift it in on the low end, and see if there's - # a byte ready for output. - quad_pos = (quad_pos + 1) & 3 - leftchar = (leftchar << 6) | n - leftbits += 6 - # - if leftbits >= 8: - leftbits -= 8 - res.append((leftchar >> leftbits).to_bytes(1, 'big')) - leftchar &= ((1 << leftbits) - 1) - # - last_char_was_a_pad = False - else: - if leftbits != 0: - raise Exception("Incorrect padding") - - return b''.join(res) - -# ____________________________________________________________ - -table_b2a_base64 = ( - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") - -def b2a_base64(bin): - "Base64-code line of data." - - newlength = (len(bin) + 2) // 3 - newlength = newlength * 4 + 1 - res = [] - - leftchar = 0 - leftbits = 0 - for c in bin: - # Shift into our buffer, and output any 6bits ready - leftchar = (leftchar << 8) | c - leftbits += 8 - res.append(table_b2a_base64[(leftchar >> (leftbits-6)) & 0x3f]) - leftbits -= 6 - if leftbits >= 6: - res.append(table_b2a_base64[(leftchar >> (leftbits-6)) & 0x3f]) - leftbits -= 6 - # - if leftbits == 2: - res.append(table_b2a_base64[(leftchar & 3) << 4]) - res.append(PAD) - res.append(PAD) - elif leftbits == 4: - res.append(table_b2a_base64[(leftchar & 0xf) << 2]) - res.append(PAD) - res.append('\n') - return ''.join(res).encode('ascii') diff --git a/binascii/metadata.txt b/binascii/metadata.txt deleted file mode 100644 index 917f31cea..000000000 --- a/binascii/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=pypy -type=module -version = 2.4.0-5 diff --git a/binascii/setup.py b/binascii/setup.py deleted file mode 100644 index 404d46e49..000000000 --- a/binascii/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-binascii', - version='2.4.0-5', - description='PyPy binascii module ported to MicroPython', - long_description='This is a module ported from PyPy standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='PyPy Developers', - author_email='pypy-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['binascii']) diff --git a/binhex/binhex.py b/binhex/binhex.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/binhex/setup.py b/binhex/setup.py deleted file mode 100644 index 6ed9e7a34..000000000 --- a/binhex/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-binhex', - version='0.0.2', - description='Dummy binhex module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['binhex']) diff --git a/bisect/setup.py b/bisect/setup.py deleted file mode 100644 index 10d782e53..000000000 --- a/bisect/setup.py +++ /dev/null @@ -1,23 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise distutils will peek up our -# module instead of system. -sys.path.pop(0) -from setuptools import setup - - -def desc_dummy(name): - return 'Dummy %s module to MicroPython' % name -def desc_cpython(name): - return 'CPython %s module ported to MicroPython' % name - -NAME = 'bisect' - -setup(name='micropython-' + NAME, - version='0.5', - description=desc_cpython(NAME), - url='https://github.com/micropython/micropython/issues/405', - author='CPython Developers', - maintainer='MicroPython Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - py_modules=[NAME]) diff --git a/calendar/calendar.py b/calendar/calendar.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/calendar/metadata.txt b/calendar/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/calendar/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/calendar/setup.py b/calendar/setup.py deleted file mode 100644 index 089b5822f..000000000 --- a/calendar/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-calendar', - version='0.0.1', - description='Dummy calendar module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['calendar']) diff --git a/cgi/setup.py b/cgi/setup.py deleted file mode 100644 index 128b28da0..000000000 --- a/cgi/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-cgi', - version='3.3.3-2', - description='CPython cgi module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['cgi']) diff --git a/cmd/setup.py b/cmd/setup.py deleted file mode 100644 index ccca50e85..000000000 --- a/cmd/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-cmd', - version='3.4.0-2', - description='CPython cmd module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['cmd']) diff --git a/code/code.py b/code/code.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/code/metadata.txt b/code/metadata.txt deleted file mode 100644 index 976088c8a..000000000 --- a/code/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.0 diff --git a/code/setup.py b/code/setup.py deleted file mode 100644 index 7dac8be20..000000000 --- a/code/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-code', - version='0.0.0', - description='Dummy code module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['code']) diff --git a/codecs/codecs.py b/codecs/codecs.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/codecs/metadata.txt b/codecs/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/codecs/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/codecs/setup.py b/codecs/setup.py deleted file mode 100644 index 602583ed4..000000000 --- a/codecs/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-codecs', - version='0.0.1', - description='Dummy codecs module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['codecs']) diff --git a/codeop/codeop.py b/codeop/codeop.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/codeop/metadata.txt b/codeop/metadata.txt deleted file mode 100644 index 976088c8a..000000000 --- a/codeop/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.0 diff --git a/codeop/setup.py b/codeop/setup.py deleted file mode 100644 index 7b5b03d4c..000000000 --- a/codeop/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-codeop', - version='0.0.0', - description='Dummy codeop module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['codeop']) diff --git a/collections.defaultdict/setup.py b/collections.defaultdict/setup.py deleted file mode 100644 index 9139f1368..000000000 --- a/collections.defaultdict/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-collections.defaultdict', - version='0.3', - description='collections.defaultdict module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['collections']) diff --git a/collections.deque/setup.py b/collections.deque/setup.py deleted file mode 100644 index 4a5f7b550..000000000 --- a/collections.deque/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-collections.deque', - version='0.1.3', - description='collections.deque module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['collections']) diff --git a/collections/setup.py b/collections/setup.py deleted file mode 100644 index f3d872635..000000000 --- a/collections/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-collections', - version='0.1.2', - description='collections module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['collections']) diff --git a/concurrent.futures/concurrent/futures/__init__.py b/concurrent.futures/concurrent/futures/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/concurrent.futures/metadata.txt b/concurrent.futures/metadata.txt deleted file mode 100644 index 0dc8fe82e..000000000 --- a/concurrent.futures/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=package -version = 0.0.1 diff --git a/concurrent.futures/setup.py b/concurrent.futures/setup.py deleted file mode 100644 index 80508a64e..000000000 --- a/concurrent.futures/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-concurrent.futures', - version='0.0.1', - description='Dummy concurrent.futures module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['concurrent']) diff --git a/contextlib/setup.py b/contextlib/setup.py deleted file mode 100644 index 943706164..000000000 --- a/contextlib/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-contextlib', - version='3.4.2-4', - description='CPython contextlib module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['contextlib'], - install_requires=['micropython-ucontextlib', 'micropython-collections']) diff --git a/copy/setup.py b/copy/setup.py deleted file mode 100644 index c84c35eb4..000000000 --- a/copy/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-copy', - version='3.3.3-2', - description='CPython copy module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['copy']) diff --git a/cpython-uasyncio/example_yield_coro.py b/cpython-uasyncio/example_yield_coro.py deleted file mode 100644 index 2291162a4..000000000 --- a/cpython-uasyncio/example_yield_coro.py +++ /dev/null @@ -1,21 +0,0 @@ -import uasyncio as asyncio - - -def run1(): - for i in range(1): - print('Hello World') - yield from asyncio.sleep(2) - print("run1 finished") - -def run2(): - for i in range(3): - print('bar') - yield run1() - yield from asyncio.sleep(1) - - -import logging -logging.basicConfig(level=logging.INFO) -loop = asyncio.get_event_loop() -loop.create_task(run2()) -loop.run_forever() diff --git a/cpython-uasyncio/metadata.txt b/cpython-uasyncio/metadata.txt deleted file mode 100644 index 2176b99e9..000000000 --- a/cpython-uasyncio/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = cpython-backport -type = module -version = 0.2.1 diff --git a/cpython-uasyncio/patch.diff b/cpython-uasyncio/patch.diff deleted file mode 100644 index be874237f..000000000 --- a/cpython-uasyncio/patch.diff +++ /dev/null @@ -1,27 +0,0 @@ -This patch shows changes done to asyncio.tasks.Task._step() from CPython 3.4.2. - ---- tasks.py 2015-01-01 10:51:40.707114866 +0200 -+++ uasyncio.py 2015-01-01 10:54:20.172402890 +0200 -@@ -46,13 +55,16 @@ - # Bare yield relinquishes control for one event loop iteration. - self._loop.call_soon(self._step) - elif inspect.isgenerator(result): -+ #print("Scheduling", result) -+ self._loop.create_task(result) -+ self._loop.call_soon(self._step) - # Yielding a generator is just wrong. -- self._loop.call_soon( -- self._step, None, -- RuntimeError( -- 'yield was used instead of yield from for ' -- 'generator in task {!r} with {}'.format( -- self, result))) -+# self._loop.call_soon( -+# self._step, None, -+# RuntimeError( -+# 'yield was used instead of yield from for ' -+# 'generator in task {!r} with {}'.format( -+# self, result))) - else: - # Yielding something else is an error. - self._loop.call_soon( diff --git a/cpython-uasyncio/setup.py b/cpython-uasyncio/setup.py deleted file mode 100644 index caa7ebb5c..000000000 --- a/cpython-uasyncio/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-cpython-uasyncio', - version='0.2.1', - description='MicroPython module uasyncio ported to CPython', - long_description='This is MicroPython compatibility module, allowing applications using\nMicroPython-specific features to run on CPython.\n', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['uasyncio']) diff --git a/cpython-uasyncio/uasyncio.py b/cpython-uasyncio/uasyncio.py deleted file mode 100644 index fc83456f7..000000000 --- a/cpython-uasyncio/uasyncio.py +++ /dev/null @@ -1,99 +0,0 @@ -import inspect -import asyncio -import asyncio.futures as futures -from asyncio import * - - -OrgTask = Task - -class Task(OrgTask): - - def _step(self, value=None, exc=None): - assert not self.done(), \ - '_step(): already done: {!r}, {!r}, {!r}'.format(self, value, exc) - if self._must_cancel: - if not isinstance(exc, futures.CancelledError): - exc = futures.CancelledError() - self._must_cancel = False - coro = self._coro - self._fut_waiter = None - - self.__class__._current_tasks[self._loop] = self - # Call either coro.throw(exc) or coro.send(value). - try: - if exc is not None: - result = coro.throw(exc) - elif value is not None: - result = coro.send(value) - else: - result = next(coro) - except StopIteration as exc: - self.set_result(exc.value) - except futures.CancelledError as exc: - super().cancel() # I.e., Future.cancel(self). - except Exception as exc: - self.set_exception(exc) - except BaseException as exc: - self.set_exception(exc) - raise - else: - if isinstance(result, futures.Future): - # Yielded Future must come from Future.__iter__(). - if result._blocking: - result._blocking = False - result.add_done_callback(self._wakeup) - self._fut_waiter = result - if self._must_cancel: - if self._fut_waiter.cancel(): - self._must_cancel = False - else: - self._loop.call_soon( - self._step, None, - RuntimeError( - 'yield was used instead of yield from ' - 'in task {!r} with {!r}'.format(self, result))) - elif result is None: - # Bare yield relinquishes control for one event loop iteration. - self._loop.call_soon(self._step) - elif inspect.isgenerator(result): - #print("Scheduling", result) - self._loop.create_task(result) - self._loop.call_soon(self._step) - # Yielding a generator is just wrong. -# self._loop.call_soon( -# self._step, None, -# RuntimeError( -# 'yield was used instead of yield from for ' -# 'generator in task {!r} with {}'.format( -# self, result))) - else: - # Yielding something else is an error. - self._loop.call_soon( - self._step, None, - RuntimeError( - 'Task got bad yield: {!r}'.format(result))) - finally: - self.__class__._current_tasks.pop(self._loop) - self = None # Needed to break cycles when an exception occurs. - - -asyncio.tasks.Task = Task - - -OrgStreamWriter = StreamWriter - -class StreamWriter(OrgStreamWriter): - - def awrite(self, data): - if isinstance(data, str): - data = data.encode("utf-8") - self.write(data) - yield from self.drain() - - def aclose(self): - self.close() - return - yield - - -asyncio.streams.StreamWriter = StreamWriter diff --git a/csv/csv.py b/csv/csv.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/csv/metadata.txt b/csv/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/csv/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/csv/setup.py b/csv/setup.py deleted file mode 100644 index a945a17e8..000000000 --- a/csv/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-csv', - version='0.0.1', - description='Dummy csv module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['csv']) diff --git a/curses.ascii/curses/ascii.py b/curses.ascii/curses/ascii.py deleted file mode 100644 index 800fd8b4b..000000000 --- a/curses.ascii/curses/ascii.py +++ /dev/null @@ -1,99 +0,0 @@ -"""Constants and membership tests for ASCII characters""" - -NUL = 0x00 # ^@ -SOH = 0x01 # ^A -STX = 0x02 # ^B -ETX = 0x03 # ^C -EOT = 0x04 # ^D -ENQ = 0x05 # ^E -ACK = 0x06 # ^F -BEL = 0x07 # ^G -BS = 0x08 # ^H -TAB = 0x09 # ^I -HT = 0x09 # ^I -LF = 0x0a # ^J -NL = 0x0a # ^J -VT = 0x0b # ^K -FF = 0x0c # ^L -CR = 0x0d # ^M -SO = 0x0e # ^N -SI = 0x0f # ^O -DLE = 0x10 # ^P -DC1 = 0x11 # ^Q -DC2 = 0x12 # ^R -DC3 = 0x13 # ^S -DC4 = 0x14 # ^T -NAK = 0x15 # ^U -SYN = 0x16 # ^V -ETB = 0x17 # ^W -CAN = 0x18 # ^X -EM = 0x19 # ^Y -SUB = 0x1a # ^Z -ESC = 0x1b # ^[ -FS = 0x1c # ^\ -GS = 0x1d # ^] -RS = 0x1e # ^^ -US = 0x1f # ^_ -SP = 0x20 # space -DEL = 0x7f # delete - -controlnames = [ -"NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL", -"BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI", -"DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", -"CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US", -"SP" -] - -def _ctoi(c): - if type(c) == type(""): - return ord(c) - else: - return c - -def isalnum(c): return isalpha(c) or isdigit(c) -def isalpha(c): return isupper(c) or islower(c) -def isascii(c): return _ctoi(c) <= 127 # ? -def isblank(c): return _ctoi(c) in (8,32) -def iscntrl(c): return _ctoi(c) <= 31 -def isdigit(c): return _ctoi(c) >= 48 and _ctoi(c) <= 57 -def isgraph(c): return _ctoi(c) >= 33 and _ctoi(c) <= 126 -def islower(c): return _ctoi(c) >= 97 and _ctoi(c) <= 122 -def isprint(c): return _ctoi(c) >= 32 and _ctoi(c) <= 126 -def ispunct(c): return _ctoi(c) != 32 and not isalnum(c) -def isspace(c): return _ctoi(c) in (9, 10, 11, 12, 13, 32) -def isupper(c): return _ctoi(c) >= 65 and _ctoi(c) <= 90 -def isxdigit(c): return isdigit(c) or \ - (_ctoi(c) >= 65 and _ctoi(c) <= 70) or (_ctoi(c) >= 97 and _ctoi(c) <= 102) -def isctrl(c): return _ctoi(c) < 32 -def ismeta(c): return _ctoi(c) > 127 - -def ascii(c): - if type(c) == type(""): - return chr(_ctoi(c) & 0x7f) - else: - return _ctoi(c) & 0x7f - -def ctrl(c): - if type(c) == type(""): - return chr(_ctoi(c) & 0x1f) - else: - return _ctoi(c) & 0x1f - -def alt(c): - if type(c) == type(""): - return chr(_ctoi(c) | 0x80) - else: - return _ctoi(c) | 0x80 - -def unctrl(c): - bits = _ctoi(c) - if bits == 0x7f: - rep = "^?" - elif isprint(bits & 0x7f): - rep = chr(bits & 0x7f) - else: - rep = "^" + chr(((bits & 0x7f) | 0x20) + 0x20) - if bits & 0x80: - return "!" + rep - return rep diff --git a/curses.ascii/setup.py b/curses.ascii/setup.py deleted file mode 100644 index 58dc86f60..000000000 --- a/curses.ascii/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-curses.ascii', - version='3.4.2-1', - description='CPython curses.ascii module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['curses']) diff --git a/curses/metadata.txt b/curses/metadata.txt deleted file mode 100644 index 976088c8a..000000000 --- a/curses/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.0 diff --git a/curses/setup.py b/curses/setup.py deleted file mode 100644 index 50a087ef5..000000000 --- a/curses/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-curses', - version='0.0.0', - description='Dummy curses module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['curses']) diff --git a/datetime/setup.py b/datetime/setup.py deleted file mode 100644 index 285a6b27c..000000000 --- a/datetime/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-datetime', - version='3.3.3-1', - description='CPython datetime module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['datetime']) diff --git a/dbm/dbm.py b/dbm/dbm.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/dbm/metadata.txt b/dbm/metadata.txt deleted file mode 100644 index fda992a9c..000000000 --- a/dbm/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.2 diff --git a/dbm/setup.py b/dbm/setup.py deleted file mode 100644 index 27fa29f4f..000000000 --- a/dbm/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-dbm', - version='0.0.2', - description='Dummy dbm module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['dbm']) diff --git a/decimal/decimal.py b/decimal/decimal.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/decimal/metadata.txt b/decimal/metadata.txt deleted file mode 100644 index fda992a9c..000000000 --- a/decimal/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.2 diff --git a/decimal/setup.py b/decimal/setup.py deleted file mode 100644 index de8d75fbe..000000000 --- a/decimal/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-decimal', - version='0.0.2', - description='Dummy decimal module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['decimal']) diff --git a/difflib/difflib.py b/difflib/difflib.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/difflib/metadata.txt b/difflib/metadata.txt deleted file mode 100644 index fda992a9c..000000000 --- a/difflib/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.2 diff --git a/difflib/setup.py b/difflib/setup.py deleted file mode 100644 index d005d117d..000000000 --- a/difflib/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-difflib', - version='0.0.2', - description='Dummy difflib module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['difflib']) diff --git a/dis/metadata.txt b/dis/metadata.txt deleted file mode 100644 index 976088c8a..000000000 --- a/dis/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.0 diff --git a/dis/setup.py b/dis/setup.py deleted file mode 100644 index d6353ac6e..000000000 --- a/dis/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-dis', - version='0.0.0', - description='Dummy dis module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['dis']) diff --git a/dummy_threading/metadata.txt b/dummy_threading/metadata.txt deleted file mode 100644 index 976088c8a..000000000 --- a/dummy_threading/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.0 diff --git a/dummy_threading/setup.py b/dummy_threading/setup.py deleted file mode 100644 index c00e93c74..000000000 --- a/dummy_threading/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-dummy_threading', - version='0.0.0', - description='Dummy dummy_threading module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['dummy_threading']) diff --git a/email.charset/setup.py b/email.charset/setup.py deleted file mode 100644 index c3288c1f2..000000000 --- a/email.charset/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-email.charset', - version='0.5.1', - description='CPython email.charset module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['email'], - install_requires=['micropython-functools', 'micropython-email.encoders', 'micropython-email.errors']) diff --git a/email.encoders/setup.py b/email.encoders/setup.py deleted file mode 100644 index dff3a5cea..000000000 --- a/email.encoders/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-email.encoders', - version='0.5.1', - description='CPython email.encoders module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['email'], - install_requires=['micropython-base64', 'micropython-binascii', 'micropython-quopri', 'micropython-re-pcre', 'micropython-string']) diff --git a/email.errors/setup.py b/email.errors/setup.py deleted file mode 100644 index 5b75307f6..000000000 --- a/email.errors/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-email.errors', - version='0.5.1', - description='CPython email.errors module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['email']) diff --git a/email.feedparser/setup.py b/email.feedparser/setup.py deleted file mode 100644 index ecf4b543c..000000000 --- a/email.feedparser/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-email.feedparser', - version='0.5.1', - description='CPython email.feedparser module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['email'], - install_requires=['micropython-re-pcre', 'micropython-email.errors', 'micropython-email.message', 'micropython-email.internal']) diff --git a/email.header/setup.py b/email.header/setup.py deleted file mode 100644 index d38aa4ce3..000000000 --- a/email.header/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-email.header', - version='0.5.2', - description='CPython email.header module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['email'], - install_requires=['micropython-re-pcre', 'micropython-binascii', 'micropython-email.encoders', 'micropython-email.errors', 'micropython-email.charset']) diff --git a/email.internal/setup.py b/email.internal/setup.py deleted file mode 100644 index 14ee3d17b..000000000 --- a/email.internal/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-email.internal', - version='0.5.1', - description='CPython email.internal module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['email'], - install_requires=['micropython-re-pcre', 'micropython-base64', 'micropython-binascii', 'micropython-functools', 'micropython-string', 'micropython-calendar', 'micropython-abc', 'micropython-email.errors', 'micropython-email.header', 'micropython-email.charset', 'micropython-email.utils']) diff --git a/email.message/setup.py b/email.message/setup.py deleted file mode 100644 index 0dadfdd0e..000000000 --- a/email.message/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-email.message', - version='0.5.3', - description='CPython email.message module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['email'], - install_requires=['micropython-re-pcre', 'micropython-uu', 'micropython-base64', 'micropython-binascii', 'micropython-email.utils', 'micropython-email.errors', 'micropython-email.charset']) diff --git a/email.parser/setup.py b/email.parser/setup.py deleted file mode 100644 index bd338e793..000000000 --- a/email.parser/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-email.parser', - version='0.5.1', - description='CPython email.parser module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['email'], - install_requires=['micropython-warnings', 'micropython-email.feedparser', 'micropython-email.message', 'micropython-email.internal']) diff --git a/email.utils/setup.py b/email.utils/setup.py deleted file mode 100644 index 2905f8b46..000000000 --- a/email.utils/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-email.utils', - version='3.3.3-2', - description='CPython email.utils module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['email'], - install_requires=['micropython-os', 'micropython-re-pcre', 'micropython-base64', 'micropython-random', 'micropython-datetime', 'micropython-urllib.parse', 'micropython-warnings', 'micropython-quopri', 'micropython-email.charset']) diff --git a/errno/errno.py b/errno/errno.py deleted file mode 100644 index 7b7935ef8..000000000 --- a/errno/errno.py +++ /dev/null @@ -1,38 +0,0 @@ -EPERM = 1 # Operation not permitted -ENOENT = 2 # No such file or directory -ESRCH = 3 # No such process -EINTR = 4 # Interrupted system call -EIO = 5 # I/O error -ENXIO = 6 # No such device or address -E2BIG = 7 # Argument list too long -ENOEXEC = 8 # Exec format error -EBADF = 9 # Bad file number -ECHILD = 10 # No child processes -EAGAIN = 11 # Try again -ENOMEM = 12 # Out of memory -EACCES = 13 # Permission denied -EFAULT = 14 # Bad address -ENOTBLK = 15 # Block device required -EBUSY = 16 # Device or resource busy -EEXIST = 17 # File exists -EXDEV = 18 # Cross-device link -ENODEV = 19 # No such device -ENOTDIR = 20 # Not a directory -EISDIR = 21 # Is a directory -EINVAL = 22 # Invalid argument -ENFILE = 23 # File table overflow -EMFILE = 24 # Too many open files -ENOTTY = 25 # Not a typewriter -ETXTBSY = 26 # Text file busy -EFBIG = 27 # File too large -ENOSPC = 28 # No space left on device -ESPIPE = 29 # Illegal seek -EROFS = 30 # Read-only file system -EMLINK = 31 # Too many links -EPIPE = 32 # Broken pipe -EDOM = 33 # Math argument out of domain of func -ERANGE = 34 # Math result not representable -EAFNOSUPPORT = 97 # Address family not supported by protocol -ECONNRESET = 104 # Connection timed out -ETIMEDOUT = 110 # Connection timed out -EINPROGRESS = 115 # Operation now in progress diff --git a/errno/setup.py b/errno/setup.py deleted file mode 100644 index 83220233c..000000000 --- a/errno/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-errno', - version='0.1.4', - description='errno module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['errno']) diff --git a/fcntl/setup.py b/fcntl/setup.py deleted file mode 100644 index 85a3f83b8..000000000 --- a/fcntl/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-fcntl', - version='0.0.4', - description='fcntl module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['fcntl'], - install_requires=['micropython-ffilib']) diff --git a/ffilib/setup.py b/ffilib/setup.py deleted file mode 100644 index a70d6fb6e..000000000 --- a/ffilib/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-ffilib', - version='0.1.3', - description='MicroPython FFI helper module', - long_description='MicroPython FFI helper module to easily interface with underlying shared libraries', - url='https://github.com/micropython/micropython-lib', - author='Damien George', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['ffilib']) diff --git a/fnmatch/setup.py b/fnmatch/setup.py deleted file mode 100644 index 9d4499430..000000000 --- a/fnmatch/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-fnmatch', - version='0.5.2', - description='CPython fnmatch module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['fnmatch'], - install_requires=['micropython-os', 'micropython-os.path', 'micropython-re-pcre']) diff --git a/fnmatch/test_fnmatch.py b/fnmatch/test_fnmatch.py deleted file mode 100644 index 4568bb17d..000000000 --- a/fnmatch/test_fnmatch.py +++ /dev/null @@ -1,90 +0,0 @@ -"""Test cases for the fnmatch module.""" - -from test import support -import unittest - -from fnmatch import fnmatch, fnmatchcase, translate, filter - -class FnmatchTestCase(unittest.TestCase): - - def check_match(self, filename, pattern, should_match=1, fn=fnmatch): - if should_match: - self.assertTrue(fn(filename, pattern), - "expected %r to match pattern %r" - % (filename, pattern)) - else: - self.assertTrue(not fn(filename, pattern), - "expected %r not to match pattern %r" - % (filename, pattern)) - - def test_fnmatch(self): - check = self.check_match - check('abc', 'abc') - check('abc', '?*?') - check('abc', '???*') - check('abc', '*???') - check('abc', '???') - check('abc', '*') - check('abc', 'ab[cd]') - check('abc', 'ab[!de]') - check('abc', 'ab[de]', 0) - check('a', '??', 0) - check('a', 'b', 0) - - # these test that '\' is handled correctly in character sets; - # see SF bug #409651 - check('\\', r'[\]') - check('a', r'[!\]') - check('\\', r'[!\]', 0) - - # test that filenames with newlines in them are handled correctly. - # http://bugs.python.org/issue6665 - check('foo\nbar', 'foo*') - check('foo\nbar\n', 'foo*') - check('\nfoo', 'foo*', False) - check('\n', '*') - - def _test_mix_bytes_str(self): - self.assertRaises(TypeError, fnmatch, 'test', b'*') - self.assertRaises(TypeError, fnmatch, b'test', '*') - self.assertRaises(TypeError, fnmatchcase, 'test', b'*') - self.assertRaises(TypeError, fnmatchcase, b'test', '*') - - def test_fnmatchcase(self): - check = self.check_match - check('AbC', 'abc', 0, fnmatchcase) - check('abc', 'AbC', 0, fnmatchcase) - - @unittest.skip("unsupported on MicroPython") - def test_bytes(self): - self.check_match(b'test', b'te*') - self.check_match(b'test\xff', b'te*\xff') - self.check_match(b'foo\nbar', b'foo*') - -class TranslateTestCase(unittest.TestCase): - - def test_translate(self): - self.assertEqual(translate('*'), '(?ms).*\Z') - self.assertEqual(translate('?'), '(?ms).\Z') - self.assertEqual(translate('a?b*'), '(?ms)a.b.*\Z') - self.assertEqual(translate('[abc]'), '(?ms)[abc]\Z') - self.assertEqual(translate('[]]'), '(?ms)[]]\Z') - self.assertEqual(translate('[!x]'), '(?ms)[^x]\Z') - self.assertEqual(translate('[^x]'), '(?ms)[\\^x]\Z') - self.assertEqual(translate('[x'), '(?ms)\\[x\Z') - - -class FilterTestCase(unittest.TestCase): - - def test_filter(self): - self.assertEqual(filter(['a', 'b'], 'a'), ['a']) - - -def test_main(): - support.run_unittest(FnmatchTestCase, - TranslateTestCase, - FilterTestCase) - - -if __name__ == "__main__": - test_main() diff --git a/formatter/formatter.py b/formatter/formatter.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/formatter/metadata.txt b/formatter/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/formatter/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/formatter/setup.py b/formatter/setup.py deleted file mode 100644 index 727461c56..000000000 --- a/formatter/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-formatter', - version='0.0.1', - description='Dummy formatter module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['formatter']) diff --git a/fractions/fractions.py b/fractions/fractions.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/fractions/metadata.txt b/fractions/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/fractions/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/fractions/setup.py b/fractions/setup.py deleted file mode 100644 index 3943bbee0..000000000 --- a/fractions/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-fractions', - version='0.0.1', - description='Dummy fractions module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['fractions']) diff --git a/ftplib/ftplib.py b/ftplib/ftplib.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/ftplib/metadata.txt b/ftplib/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/ftplib/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/ftplib/setup.py b/ftplib/setup.py deleted file mode 100644 index 1b9c2e0ac..000000000 --- a/ftplib/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-ftplib', - version='0.0.1', - description='Dummy ftplib module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['ftplib']) diff --git a/functools/setup.py b/functools/setup.py deleted file mode 100644 index 0e8aec555..000000000 --- a/functools/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-functools', - version='0.0.7', - description='functools module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['functools']) diff --git a/getopt/setup.py b/getopt/setup.py deleted file mode 100644 index 89862bf43..000000000 --- a/getopt/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-getopt', - version='3.3.3-1', - description='CPython getopt module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['getopt'], - install_requires=['micropython-os']) diff --git a/getpass/getpass.py b/getpass/getpass.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/getpass/metadata.txt b/getpass/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/getpass/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/getpass/setup.py b/getpass/setup.py deleted file mode 100644 index 94a09ea7c..000000000 --- a/getpass/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-getpass', - version='0.0.1', - description='Dummy getpass module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['getpass']) diff --git a/gettext/setup.py b/gettext/setup.py deleted file mode 100644 index ecec0c516..000000000 --- a/gettext/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-gettext', - version='0.1', - description='gettext module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Riccardo Magliocchetti', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['gettext'], - install_requires=['micropython-ffilib']) diff --git a/gettext/test_gettext.py b/gettext/test_gettext.py deleted file mode 100644 index 5dd68a13d..000000000 --- a/gettext/test_gettext.py +++ /dev/null @@ -1,16 +0,0 @@ -import gettext - -msg = gettext.gettext('yes') -assert msg == 'yes' - -msg = gettext.ngettext('one', 'two', 1) -assert msg == 'one' - -msg = gettext.ngettext('one', 'two', 2) -assert msg == 'two' - -msg = gettext.ngettext('one', 'two', 0) -assert msg == 'two' - -msg = gettext.ngettext('one', 'two', 'three') -assert msg == 'two' diff --git a/glob/setup.py b/glob/setup.py deleted file mode 100644 index 00df42d01..000000000 --- a/glob/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-glob', - version='0.5.2', - description='CPython glob module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['glob'], - install_requires=['micropython-os', 'micropython-re-pcre', 'micropython-fnmatch']) diff --git a/glob/test_glob.py b/glob/test_glob.py deleted file mode 100644 index ec00e4ac6..000000000 --- a/glob/test_glob.py +++ /dev/null @@ -1,181 +0,0 @@ -import glob -import os -import os.path -import shutil -import sys -import unittest - -from test.support import (run_unittest, TESTFN, skip_unless_symlink, - can_symlink, create_empty_file) - - -class GlobTests(unittest.TestCase): - - def norm(self, *parts): - return os.path.normpath(os.path.join(self.tempdir, *parts)) - - def mktemp(self, *parts): - filename = self.norm(*parts) - base, file = os.path.split(filename) - if not os.path.exists(base): - os.makedirs(base) - create_empty_file(filename) - - def setUp(self): - self.tempdir = TESTFN + "_dir" - self.mktemp('a', 'D') - self.mktemp('aab', 'F') - self.mktemp('.aa', 'G') - self.mktemp('.bb', 'H') - self.mktemp('aaa', 'zzzF') - self.mktemp('ZZZ') - self.mktemp('a', 'bcd', 'EF') - self.mktemp('a', 'bcd', 'efg', 'ha') - if can_symlink(): - os.symlink(self.norm('broken'), self.norm('sym1')) - os.symlink('broken', self.norm('sym2')) - os.symlink(os.path.join('a', 'bcd'), self.norm('sym3')) - - def tearDown(self): - shutil.rmtree(self.tempdir) - - def glob(self, *parts): - if len(parts) == 1: - pattern = parts[0] - else: - pattern = os.path.join(*parts) - p = os.path.join(self.tempdir, pattern) - res = glob.glob(p) - self.assertEqual(list(glob.iglob(p)), res) - bres = [os.fsencode(x) for x in res] -# Bytes globbing is not support on MicroPython -# self.assertEqual(glob.glob(os.fsencode(p)), bres) -# self.assertEqual(list(glob.iglob(os.fsencode(p))), bres) - return res - - def assertSequencesEqual_noorder(self, l1, l2): - l1 = list(l1) - l2 = list(l2) - self.assertEqual(set(l1), set(l2)) - self.assertEqual(sorted(l1), sorted(l2)) - - def test_glob_literal(self): - eq = self.assertSequencesEqual_noorder - eq(self.glob('a'), [self.norm('a')]) - eq(self.glob('a', 'D'), [self.norm('a', 'D')]) - eq(self.glob('aab'), [self.norm('aab')]) - eq(self.glob('zymurgy'), []) - - res = glob.glob('*') - self.assertEqual({type(r) for r in res}, {str}) - res = glob.glob(os.path.join(os.curdir, '*')) - self.assertEqual({type(r) for r in res}, {str}) - -# res = glob.glob(b'*') -# self.assertEqual({type(r) for r in res}, {bytes}) -# res = glob.glob(os.path.join(os.fsencode(os.curdir), b'*')) -# self.assertEqual({type(r) for r in res}, {bytes}) - - def test_glob_one_directory(self): - eq = self.assertSequencesEqual_noorder - eq(self.glob('a*'), map(self.norm, ['a', 'aab', 'aaa'])) - eq(self.glob('*a'), map(self.norm, ['a', 'aaa'])) - eq(self.glob('.*'), map(self.norm, ['.aa', '.bb'])) - eq(self.glob('?aa'), map(self.norm, ['aaa'])) - eq(self.glob('aa?'), map(self.norm, ['aaa', 'aab'])) - eq(self.glob('aa[ab]'), map(self.norm, ['aaa', 'aab'])) - eq(self.glob('*q'), []) - - def test_glob_nested_directory(self): - eq = self.assertSequencesEqual_noorder - if os.path.normcase("abCD") == "abCD": - # case-sensitive filesystem - eq(self.glob('a', 'bcd', 'E*'), [self.norm('a', 'bcd', 'EF')]) - else: - # case insensitive filesystem - eq(self.glob('a', 'bcd', 'E*'), [self.norm('a', 'bcd', 'EF'), - self.norm('a', 'bcd', 'efg')]) - eq(self.glob('a', 'bcd', '*g'), [self.norm('a', 'bcd', 'efg')]) - - def test_glob_directory_names(self): - eq = self.assertSequencesEqual_noorder - eq(self.glob('*', 'D'), [self.norm('a', 'D')]) - eq(self.glob('*', '*a'), []) - eq(self.glob('a', '*', '*', '*a'), - [self.norm('a', 'bcd', 'efg', 'ha')]) - eq(self.glob('?a?', '*F'), [self.norm('aaa', 'zzzF'), - self.norm('aab', 'F')]) - - def test_glob_directory_with_trailing_slash(self): - # Patterns ending with a slash shouldn't match non-dirs - res = glob.glob(self.norm('Z*Z') + os.sep) - self.assertEqual(res, []) - res = glob.glob(self.norm('ZZZ') + os.sep) - self.assertEqual(res, []) - # When there is a wildcard pattern which ends with os.sep, glob() - # doesn't blow up. - res = glob.glob(self.norm('aa*') + os.sep) - self.assertEqual(len(res), 2) - # either of these results is reasonable - self.assertIn(set(res), [ - {self.norm('aaa'), self.norm('aab')}, - {self.norm('aaa') + os.sep, self.norm('aab') + os.sep}, - ]) - - @unittest.skip("unsupported on MicroPython") - def test_glob_bytes_directory_with_trailing_slash(self): - # Same as test_glob_directory_with_trailing_slash, but with a - # bytes argument. - res = glob.glob(os.fsencode(self.norm('Z*Z') + os.sep)) - self.assertEqual(res, []) - res = glob.glob(os.fsencode(self.norm('ZZZ') + os.sep)) - self.assertEqual(res, []) - res = glob.glob(os.fsencode(self.norm('aa*') + os.sep)) - self.assertEqual(len(res), 2) - # either of these results is reasonable - self.assertIn(set(res), [ - {os.fsencode(self.norm('aaa')), - os.fsencode(self.norm('aab'))}, - {os.fsencode(self.norm('aaa') + os.sep), - os.fsencode(self.norm('aab') + os.sep)}, - ]) - - @skip_unless_symlink - def test_glob_symlinks(self): - eq = self.assertSequencesEqual_noorder - eq(self.glob('sym3'), [self.norm('sym3')]) - eq(self.glob('sym3', '*'), [self.norm('sym3', 'EF'), - self.norm('sym3', 'efg')]) - self.assertIn(self.glob('sym3' + os.sep), - [[self.norm('sym3')], [self.norm('sym3') + os.sep]]) - eq(self.glob('*', '*F'), - [self.norm('aaa', 'zzzF'), - self.norm('aab', 'F'), self.norm('sym3', 'EF')]) - - @skip_unless_symlink - def test_glob_broken_symlinks(self): - eq = self.assertSequencesEqual_noorder - eq(self.glob('sym*'), [self.norm('sym1'), self.norm('sym2'), - self.norm('sym3')]) - eq(self.glob('sym1'), [self.norm('sym1')]) - eq(self.glob('sym2'), [self.norm('sym2')]) - - @unittest.skipUnless(sys.platform == "win32", "Win32 specific test") - def test_glob_magic_in_drive(self): - eq = self.assertSequencesEqual_noorder - eq(glob.glob('*:'), []) - eq(glob.glob(b'*:'), []) - eq(glob.glob('?:'), []) - eq(glob.glob(b'?:'), []) - eq(glob.glob('\\\\?\\c:\\'), ['\\\\?\\c:\\']) - eq(glob.glob(b'\\\\?\\c:\\'), [b'\\\\?\\c:\\']) - eq(glob.glob('\\\\*\\*\\'), []) - eq(glob.glob(b'\\\\*\\*\\'), []) - - -def test_main(): - run_unittest(GlobTests) - - -if __name__ == "__main__": - test_main() diff --git a/gzip/setup.py b/gzip/setup.py deleted file mode 100644 index 6efe11b3b..000000000 --- a/gzip/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-gzip', - version='0.1.1', - description='gzip module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['gzip']) diff --git a/hashlib/hashlib/_sha256.py b/hashlib/hashlib/_sha256.py deleted file mode 100644 index 8c013b5fd..000000000 --- a/hashlib/hashlib/_sha256.py +++ /dev/null @@ -1,264 +0,0 @@ -SHA_BLOCKSIZE = 64 -SHA_DIGESTSIZE = 32 - - -def new_shaobject(): - return { - 'digest': [0]*8, - 'count_lo': 0, - 'count_hi': 0, - 'data': [0]* SHA_BLOCKSIZE, - 'local': 0, - 'digestsize': 0 - } - -ROR = lambda x, y: (((x & 0xffffffff) >> (y & 31)) | (x << (32 - (y & 31)))) & 0xffffffff -Ch = lambda x, y, z: (z ^ (x & (y ^ z))) -Maj = lambda x, y, z: (((x | y) & z) | (x & y)) -S = lambda x, n: ROR(x, n) -R = lambda x, n: (x & 0xffffffff) >> n -Sigma0 = lambda x: (S(x, 2) ^ S(x, 13) ^ S(x, 22)) -Sigma1 = lambda x: (S(x, 6) ^ S(x, 11) ^ S(x, 25)) -Gamma0 = lambda x: (S(x, 7) ^ S(x, 18) ^ R(x, 3)) -Gamma1 = lambda x: (S(x, 17) ^ S(x, 19) ^ R(x, 10)) - -def sha_transform(sha_info): - W = [] - - d = sha_info['data'] - for i in range(0,16): - W.append( (d[4*i]<<24) + (d[4*i+1]<<16) + (d[4*i+2]<<8) + d[4*i+3]) - - for i in range(16,64): - W.append( (Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]) & 0xffffffff ) - - ss = sha_info['digest'][:] - - def RND(a,b,c,d,e,f,g,h,i,ki): - t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i]; - t1 = Sigma0(a) + Maj(a, b, c); - d += t0; - h = t0 + t1; - return d & 0xffffffff, h & 0xffffffff - - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],0,0x428a2f98); - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],1,0x71374491); - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],2,0xb5c0fbcf); - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],3,0xe9b5dba5); - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],4,0x3956c25b); - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],5,0x59f111f1); - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],6,0x923f82a4); - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],7,0xab1c5ed5); - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],8,0xd807aa98); - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],9,0x12835b01); - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],10,0x243185be); - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],11,0x550c7dc3); - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],12,0x72be5d74); - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],13,0x80deb1fe); - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],14,0x9bdc06a7); - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],15,0xc19bf174); - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],16,0xe49b69c1); - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],17,0xefbe4786); - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],18,0x0fc19dc6); - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],19,0x240ca1cc); - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],20,0x2de92c6f); - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],21,0x4a7484aa); - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],22,0x5cb0a9dc); - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],23,0x76f988da); - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],24,0x983e5152); - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],25,0xa831c66d); - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],26,0xb00327c8); - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],27,0xbf597fc7); - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],28,0xc6e00bf3); - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],29,0xd5a79147); - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],30,0x06ca6351); - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],31,0x14292967); - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],32,0x27b70a85); - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],33,0x2e1b2138); - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],34,0x4d2c6dfc); - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],35,0x53380d13); - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],36,0x650a7354); - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],37,0x766a0abb); - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],38,0x81c2c92e); - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],39,0x92722c85); - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],40,0xa2bfe8a1); - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],41,0xa81a664b); - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],42,0xc24b8b70); - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],43,0xc76c51a3); - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],44,0xd192e819); - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],45,0xd6990624); - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],46,0xf40e3585); - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],47,0x106aa070); - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],48,0x19a4c116); - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],49,0x1e376c08); - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],50,0x2748774c); - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],51,0x34b0bcb5); - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],52,0x391c0cb3); - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],53,0x4ed8aa4a); - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],54,0x5b9cca4f); - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],55,0x682e6ff3); - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],56,0x748f82ee); - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],57,0x78a5636f); - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],58,0x84c87814); - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],59,0x8cc70208); - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],60,0x90befffa); - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],61,0xa4506ceb); - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],62,0xbef9a3f7); - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],63,0xc67178f2); - - dig = [] - for i, x in enumerate(sha_info['digest']): - dig.append( (x + ss[i]) & 0xffffffff ) - sha_info['digest'] = dig - -def sha_init(): - sha_info = new_shaobject() - sha_info['digest'] = [0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19] - sha_info['count_lo'] = 0 - sha_info['count_hi'] = 0 - sha_info['local'] = 0 - sha_info['digestsize'] = 32 - return sha_info - -def sha224_init(): - sha_info = new_shaobject() - sha_info['digest'] = [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4] - sha_info['count_lo'] = 0 - sha_info['count_hi'] = 0 - sha_info['local'] = 0 - sha_info['digestsize'] = 28 - return sha_info - -def getbuf(s): - if isinstance(s, str): - return s.encode('ascii') - else: - return bytes(s) - -def sha_update(sha_info, buffer): - if isinstance(buffer, str): - raise TypeError("Unicode strings must be encoded before hashing") - count = len(buffer) - buffer_idx = 0 - clo = (sha_info['count_lo'] + (count << 3)) & 0xffffffff - if clo < sha_info['count_lo']: - sha_info['count_hi'] += 1 - sha_info['count_lo'] = clo - - sha_info['count_hi'] += (count >> 29) - - if sha_info['local']: - i = SHA_BLOCKSIZE - sha_info['local'] - if i > count: - i = count - - # copy buffer - for x in enumerate(buffer[buffer_idx:buffer_idx+i]): - sha_info['data'][sha_info['local']+x[0]] = x[1] - - count -= i - buffer_idx += i - - sha_info['local'] += i - if sha_info['local'] == SHA_BLOCKSIZE: - sha_transform(sha_info) - sha_info['local'] = 0 - else: - return - - while count >= SHA_BLOCKSIZE: - # copy buffer - sha_info['data'] = list(buffer[buffer_idx:buffer_idx + SHA_BLOCKSIZE]) - count -= SHA_BLOCKSIZE - buffer_idx += SHA_BLOCKSIZE - sha_transform(sha_info) - - - # copy buffer - pos = sha_info['local'] - sha_info['data'][pos:pos+count] = list(buffer[buffer_idx:buffer_idx + count]) - sha_info['local'] = count - -def sha_final(sha_info): - lo_bit_count = sha_info['count_lo'] - hi_bit_count = sha_info['count_hi'] - count = (lo_bit_count >> 3) & 0x3f - sha_info['data'][count] = 0x80; - count += 1 - if count > SHA_BLOCKSIZE - 8: - # zero the bytes in data after the count - sha_info['data'] = sha_info['data'][:count] + ([0] * (SHA_BLOCKSIZE - count)) - sha_transform(sha_info) - # zero bytes in data - sha_info['data'] = [0] * SHA_BLOCKSIZE - else: - sha_info['data'] = sha_info['data'][:count] + ([0] * (SHA_BLOCKSIZE - count)) - - sha_info['data'][56] = (hi_bit_count >> 24) & 0xff - sha_info['data'][57] = (hi_bit_count >> 16) & 0xff - sha_info['data'][58] = (hi_bit_count >> 8) & 0xff - sha_info['data'][59] = (hi_bit_count >> 0) & 0xff - sha_info['data'][60] = (lo_bit_count >> 24) & 0xff - sha_info['data'][61] = (lo_bit_count >> 16) & 0xff - sha_info['data'][62] = (lo_bit_count >> 8) & 0xff - sha_info['data'][63] = (lo_bit_count >> 0) & 0xff - - sha_transform(sha_info) - - dig = [] - for i in sha_info['digest']: - dig.extend([ ((i>>24) & 0xff), ((i>>16) & 0xff), ((i>>8) & 0xff), (i & 0xff) ]) - return bytes(dig) - -class sha256(object): - digest_size = digestsize = SHA_DIGESTSIZE - block_size = SHA_BLOCKSIZE - - def __init__(self, s=None): - self._sha = sha_init() - if s: - sha_update(self._sha, getbuf(s)) - - def update(self, s): - sha_update(self._sha, getbuf(s)) - - def digest(self): - return sha_final(self._sha.copy())[:self._sha['digestsize']] - - def hexdigest(self): - return ''.join(['%.2x' % i for i in self.digest()]) - - def copy(self): - new = sha256() - new._sha = self._sha.copy() - return new - -class sha224(sha256): - digest_size = digestsize = 28 - - def __init__(self, s=None): - self._sha = sha224_init() - if s: - sha_update(self._sha, getbuf(s)) - - def copy(self): - new = sha224() - new._sha = self._sha.copy() - return new - -def test(): - a_str = "just a test string" - - assert b"\xe3\xb0\xc4B\x98\xfc\x1c\x14\x9a\xfb\xf4\xc8\x99o\xb9$'\xaeA\xe4d\x9b\x93L\xa4\x95\x99\x1bxR\xb8U" == sha256().digest() - assert 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' == sha256().hexdigest() - assert 'd7b553c6f09ac85d142415f857c5310f3bbbe7cdd787cce4b985acedd585266f' == sha256(a_str).hexdigest() - assert '8113ebf33c97daa9998762aacafe750c7cefc2b2f173c90c59663a57fe626f21' == sha256(a_str*7).hexdigest() - - s = sha256(a_str) - s.update(a_str) - assert '03d9963e05a094593190b6fc794cb1a3e1ac7d7883f0b5855268afeccc70d461' == s.hexdigest() - -if __name__ == "__main__": - test() - - diff --git a/hashlib/hashlib/_sha512.py b/hashlib/hashlib/_sha512.py deleted file mode 100644 index 8875db2e5..000000000 --- a/hashlib/hashlib/_sha512.py +++ /dev/null @@ -1,290 +0,0 @@ -""" -This code was Ported from CPython's sha512module.c -""" - -SHA_BLOCKSIZE = 128 -SHA_DIGESTSIZE = 64 - - -def new_shaobject(): - return { - 'digest': [0]*8, - 'count_lo': 0, - 'count_hi': 0, - 'data': [0]* SHA_BLOCKSIZE, - 'local': 0, - 'digestsize': 0 - } - -ROR64 = lambda x, y: (((x & 0xffffffffffffffff) >> (y & 63)) | (x << (64 - (y & 63)))) & 0xffffffffffffffff -Ch = lambda x, y, z: (z ^ (x & (y ^ z))) -Maj = lambda x, y, z: (((x | y) & z) | (x & y)) -S = lambda x, n: ROR64(x, n) -R = lambda x, n: (x & 0xffffffffffffffff) >> n -Sigma0 = lambda x: (S(x, 28) ^ S(x, 34) ^ S(x, 39)) -Sigma1 = lambda x: (S(x, 14) ^ S(x, 18) ^ S(x, 41)) -Gamma0 = lambda x: (S(x, 1) ^ S(x, 8) ^ R(x, 7)) -Gamma1 = lambda x: (S(x, 19) ^ S(x, 61) ^ R(x, 6)) - -def sha_transform(sha_info): - W = [] - - d = sha_info['data'] - for i in range(0,16): - W.append( (d[8*i]<<56) + (d[8*i+1]<<48) + (d[8*i+2]<<40) + (d[8*i+3]<<32) + (d[8*i+4]<<24) + (d[8*i+5]<<16) + (d[8*i+6]<<8) + d[8*i+7]) - - for i in range(16,80): - W.append( (Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16]) & 0xffffffffffffffff ) - - ss = sha_info['digest'][:] - - def RND(a,b,c,d,e,f,g,h,i,ki): - t0 = (h + Sigma1(e) + Ch(e, f, g) + ki + W[i]) & 0xffffffffffffffff - t1 = (Sigma0(a) + Maj(a, b, c)) & 0xffffffffffffffff - d = (d + t0) & 0xffffffffffffffff - h = (t0 + t1) & 0xffffffffffffffff - return d & 0xffffffffffffffff, h & 0xffffffffffffffff - - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],0,0x428a2f98d728ae22) - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],1,0x7137449123ef65cd) - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],2,0xb5c0fbcfec4d3b2f) - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],3,0xe9b5dba58189dbbc) - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],4,0x3956c25bf348b538) - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],5,0x59f111f1b605d019) - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],6,0x923f82a4af194f9b) - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],7,0xab1c5ed5da6d8118) - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],8,0xd807aa98a3030242) - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],9,0x12835b0145706fbe) - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],10,0x243185be4ee4b28c) - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],11,0x550c7dc3d5ffb4e2) - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],12,0x72be5d74f27b896f) - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],13,0x80deb1fe3b1696b1) - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],14,0x9bdc06a725c71235) - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],15,0xc19bf174cf692694) - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],16,0xe49b69c19ef14ad2) - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],17,0xefbe4786384f25e3) - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],18,0x0fc19dc68b8cd5b5) - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],19,0x240ca1cc77ac9c65) - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],20,0x2de92c6f592b0275) - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],21,0x4a7484aa6ea6e483) - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],22,0x5cb0a9dcbd41fbd4) - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],23,0x76f988da831153b5) - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],24,0x983e5152ee66dfab) - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],25,0xa831c66d2db43210) - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],26,0xb00327c898fb213f) - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],27,0xbf597fc7beef0ee4) - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],28,0xc6e00bf33da88fc2) - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],29,0xd5a79147930aa725) - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],30,0x06ca6351e003826f) - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],31,0x142929670a0e6e70) - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],32,0x27b70a8546d22ffc) - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],33,0x2e1b21385c26c926) - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],34,0x4d2c6dfc5ac42aed) - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],35,0x53380d139d95b3df) - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],36,0x650a73548baf63de) - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],37,0x766a0abb3c77b2a8) - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],38,0x81c2c92e47edaee6) - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],39,0x92722c851482353b) - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],40,0xa2bfe8a14cf10364) - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],41,0xa81a664bbc423001) - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],42,0xc24b8b70d0f89791) - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],43,0xc76c51a30654be30) - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],44,0xd192e819d6ef5218) - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],45,0xd69906245565a910) - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],46,0xf40e35855771202a) - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],47,0x106aa07032bbd1b8) - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],48,0x19a4c116b8d2d0c8) - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],49,0x1e376c085141ab53) - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],50,0x2748774cdf8eeb99) - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],51,0x34b0bcb5e19b48a8) - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],52,0x391c0cb3c5c95a63) - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],53,0x4ed8aa4ae3418acb) - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],54,0x5b9cca4f7763e373) - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],55,0x682e6ff3d6b2b8a3) - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],56,0x748f82ee5defb2fc) - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],57,0x78a5636f43172f60) - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],58,0x84c87814a1f0ab72) - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],59,0x8cc702081a6439ec) - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],60,0x90befffa23631e28) - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],61,0xa4506cebde82bde9) - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],62,0xbef9a3f7b2c67915) - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],63,0xc67178f2e372532b) - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],64,0xca273eceea26619c) - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],65,0xd186b8c721c0c207) - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],66,0xeada7dd6cde0eb1e) - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],67,0xf57d4f7fee6ed178) - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],68,0x06f067aa72176fba) - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],69,0x0a637dc5a2c898a6) - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],70,0x113f9804bef90dae) - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],71,0x1b710b35131c471b) - ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],72,0x28db77f523047d84) - ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],73,0x32caab7b40c72493) - ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],74,0x3c9ebe0a15c9bebc) - ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],75,0x431d67c49c100d4c) - ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],76,0x4cc5d4becb3e42b6) - ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],77,0x597f299cfc657e2a) - ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],78,0x5fcb6fab3ad6faec) - ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],79,0x6c44198c4a475817) - - dig = [] - for i, x in enumerate(sha_info['digest']): - dig.append( (x + ss[i]) & 0xffffffffffffffff ) - sha_info['digest'] = dig - -def sha_init(): - sha_info = new_shaobject() - sha_info['digest'] = [ 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179] - sha_info['count_lo'] = 0 - sha_info['count_hi'] = 0 - sha_info['local'] = 0 - sha_info['digestsize'] = 64 - return sha_info - -def sha384_init(): - sha_info = new_shaobject() - sha_info['digest'] = [ 0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939, 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4] - sha_info['count_lo'] = 0 - sha_info['count_hi'] = 0 - sha_info['local'] = 0 - sha_info['digestsize'] = 48 - return sha_info - -def getbuf(s): - if isinstance(s, str): - return s.encode('ascii') - else: - return bytes(s) - -def sha_update(sha_info, buffer): - if isinstance(buffer, str): - raise TypeError("Unicode strings must be encoded before hashing") - count = len(buffer) - buffer_idx = 0 - clo = (sha_info['count_lo'] + (count << 3)) & 0xffffffff - if clo < sha_info['count_lo']: - sha_info['count_hi'] += 1 - sha_info['count_lo'] = clo - - sha_info['count_hi'] += (count >> 29) - - if sha_info['local']: - i = SHA_BLOCKSIZE - sha_info['local'] - if i > count: - i = count - - # copy buffer - for x in enumerate(buffer[buffer_idx:buffer_idx+i]): - sha_info['data'][sha_info['local']+x[0]] = x[1] - - count -= i - buffer_idx += i - - sha_info['local'] += i - if sha_info['local'] == SHA_BLOCKSIZE: - sha_transform(sha_info) - sha_info['local'] = 0 - else: - return - - while count >= SHA_BLOCKSIZE: - # copy buffer - sha_info['data'] = list(buffer[buffer_idx:buffer_idx + SHA_BLOCKSIZE]) - count -= SHA_BLOCKSIZE - buffer_idx += SHA_BLOCKSIZE - sha_transform(sha_info) - - # copy buffer - pos = sha_info['local'] - sha_info['data'][pos:pos+count] = list(buffer[buffer_idx:buffer_idx + count]) - sha_info['local'] = count - -def sha_final(sha_info): - lo_bit_count = sha_info['count_lo'] - hi_bit_count = sha_info['count_hi'] - count = (lo_bit_count >> 3) & 0x7f - sha_info['data'][count] = 0x80; - count += 1 - if count > SHA_BLOCKSIZE - 16: - # zero the bytes in data after the count - sha_info['data'] = sha_info['data'][:count] + ([0] * (SHA_BLOCKSIZE - count)) - sha_transform(sha_info) - # zero bytes in data - sha_info['data'] = [0] * SHA_BLOCKSIZE - else: - sha_info['data'] = sha_info['data'][:count] + ([0] * (SHA_BLOCKSIZE - count)) - - sha_info['data'][112] = 0; - sha_info['data'][113] = 0; - sha_info['data'][114] = 0; - sha_info['data'][115] = 0; - sha_info['data'][116] = 0; - sha_info['data'][117] = 0; - sha_info['data'][118] = 0; - sha_info['data'][119] = 0; - - sha_info['data'][120] = (hi_bit_count >> 24) & 0xff - sha_info['data'][121] = (hi_bit_count >> 16) & 0xff - sha_info['data'][122] = (hi_bit_count >> 8) & 0xff - sha_info['data'][123] = (hi_bit_count >> 0) & 0xff - sha_info['data'][124] = (lo_bit_count >> 24) & 0xff - sha_info['data'][125] = (lo_bit_count >> 16) & 0xff - sha_info['data'][126] = (lo_bit_count >> 8) & 0xff - sha_info['data'][127] = (lo_bit_count >> 0) & 0xff - - sha_transform(sha_info) - - dig = [] - for i in sha_info['digest']: - dig.extend([ ((i>>56) & 0xff), ((i>>48) & 0xff), ((i>>40) & 0xff), ((i>>32) & 0xff), ((i>>24) & 0xff), ((i>>16) & 0xff), ((i>>8) & 0xff), (i & 0xff) ]) - return bytes(dig) - -class sha512(object): - digest_size = digestsize = SHA_DIGESTSIZE - block_size = SHA_BLOCKSIZE - - def __init__(self, s=None): - self._sha = sha_init() - if s: - sha_update(self._sha, getbuf(s)) - - def update(self, s): - sha_update(self._sha, getbuf(s)) - - def digest(self): - return sha_final(self._sha.copy())[:self._sha['digestsize']] - - def hexdigest(self): - return ''.join(['%.2x' % i for i in self.digest()]) - - def copy(self): - new = sha512() - new._sha = self._sha.copy() - return new - -class sha384(sha512): - digest_size = digestsize = 48 - - def __init__(self, s=None): - self._sha = sha384_init() - if s: - sha_update(self._sha, getbuf(s)) - - def copy(self): - new = sha384() - new._sha = self._sha.copy() - return new - -def test(): - a_str = "just a test string" - - assert sha512().digest() == b"\xcf\x83\xe15~\xef\xb8\xbd\xf1T(P\xd6m\x80\x07\xd6 \xe4\x05\x0bW\x15\xdc\x83\xf4\xa9!\xd3l\xe9\xceG\xd0\xd1<]\x85\xf2\xb0\xff\x83\x18\xd2\x87~\xec/c\xb91\xbdGAz\x81\xa582z\xf9'\xda>" - assert sha512().hexdigest() == 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e' - assert sha512(a_str).hexdigest() == '68be4c6664af867dd1d01c8d77e963d87d77b702400c8fabae355a41b8927a5a5533a7f1c28509bbd65c5f3ac716f33be271fbda0ca018b71a84708c9fae8a53' - assert sha512(a_str*7).hexdigest() == '3233acdbfcfff9bff9fc72401d31dbffa62bd24e9ec846f0578d647da73258d9f0879f7fde01fe2cc6516af3f343807fdef79e23d696c923d79931db46bf1819' - - s = sha512(a_str) - s.update(a_str) - assert s.hexdigest() == '341aeb668730bbb48127d5531115f3c39d12cb9586a6ca770898398aff2411087cfe0b570689adf328cddeb1f00803acce6737a19f310b53bbdb0320828f75bb' - -if __name__ == "__main__": - test() diff --git a/hashlib/metadata.txt b/hashlib/metadata.txt deleted file mode 100644 index e46150c7f..000000000 --- a/hashlib/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=pypy -type=package -version = 2.4.0-4 diff --git a/hashlib/setup.py b/hashlib/setup.py deleted file mode 100644 index 59fb9130b..000000000 --- a/hashlib/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-hashlib', - version='2.4.0-4', - description='PyPy hashlib module ported to MicroPython', - long_description='This is a module ported from PyPy standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='PyPy Developers', - author_email='pypy-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['hashlib']) diff --git a/hashlib/test_hashlib.py b/hashlib/test_hashlib.py deleted file mode 100644 index 1f5f9be86..000000000 --- a/hashlib/test_hashlib.py +++ /dev/null @@ -1,26 +0,0 @@ -from hashlib._sha256 import test as sha256_test -from hashlib._sha512 import test as sha512_test - - -sha256_test() -sha512_test() - - -import hashlib - -patterns = [ - ("sha224", b"1234", - b'\x99\xfb/H\xc6\xafGa\xf9\x04\xfc\x85\xf9^\xb5a\x90\xe5\xd4\x0b\x1fD\xec:\x9c\x1f\xa3\x19'), - - ("sha256", b"1234", - b'\x03\xacgB\x16\xf3\xe1\\v\x1e\xe1\xa5\xe2U\xf0g\x956#\xc8\xb3\x88\xb4E\x9e\x13\xf9x\xd7\xc8F\xf4'), - - ("sha384", b"1234", - b'PO\x00\x8c\x8f\xcf\x8b.\xd5\xdf\xcd\xe7R\xfcTd\xab\x8b\xa0d!]\x9c[_\xc4\x86\xaf=\x9a\xb8\xc8\x1b\x14xQ\x80\xd2\xad|\xee\x1a\xb7\x92\xadDy\x8c'), - - ("sha512", b"1234", - b'\xd4\x04U\x9f`.\xabo\xd6\x02\xacv\x80\xda\xcb\xfa\xad\xd1603^\x95\x1f\tz\xf3\x90\x0e\x9d\xe1v\xb6\xdb(Q/.\x00\x0b\x9d\x04\xfb\xa5\x13>\x8b\x1cn\x8d\xf5\x9d\xb3\xa8\xab\x9d`\xbeK\x97\xcc\x9e\x81\xdb'), -] - -for algo, input, output in patterns: - assert hashlib.new(algo, input).digest() == output diff --git a/heapq/setup.py b/heapq/setup.py deleted file mode 100644 index 88e152dd0..000000000 --- a/heapq/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-heapq', - version='0.9.3', - description='CPython heapq module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['heapq']) diff --git a/hmac/setup.py b/hmac/setup.py deleted file mode 100644 index d54c2fbc6..000000000 --- a/hmac/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-hmac', - version='3.4.2-3', - description='CPython hmac module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['hmac'], - install_requires=['micropython-warnings', 'micropython-hashlib']) diff --git a/hmac/test_hmac.py b/hmac/test_hmac.py deleted file mode 100644 index 52fe57e6b..000000000 --- a/hmac/test_hmac.py +++ /dev/null @@ -1,48 +0,0 @@ -import hmac -from hashlib.sha256 import sha256 -from hashlib.sha512 import sha512 - -msg = b'zlutoucky kun upel dabelske ody' - -dig = hmac.new(b'1234567890', msg=msg, digestmod=sha256).hexdigest() - -print('c735e751e36b08fb01e25794bdb15e7289b82aecdb652c8f4f72f307b39dad39') -print(dig) - -if dig != 'c735e751e36b08fb01e25794bdb15e7289b82aecdb652c8f4f72f307b39dad39': - raise Exception("Error") - -dig = hmac.new(b'1234567890', msg=msg, digestmod=sha512).hexdigest() - -print('59942f31b6f5473fb4eb630fabf5358a49bc11d24ebc83b114b4af30d6ef47ea14b673f478586f520a0b9c53b27c8f8dd618c165ef586195bd4e98293d34df1a') -print(dig) - -if dig != '59942f31b6f5473fb4eb630fabf5358a49bc11d24ebc83b114b4af30d6ef47ea14b673f478586f520a0b9c53b27c8f8dd618c165ef586195bd4e98293d34df1a': - raise Exception("Error") - -key = b'\x06\x1au\x90|Xz;o\x1b<\xafGL\xbfn\x8a\xc94YPfC^\xb9\xdd)\x7f\xaf\x85\xa1\xed\x82\xbexp\xaf\x13\x1a\x9d' - -dig = hmac.new(key[:20], msg=msg, digestmod=sha256).hexdigest() - -print('59e332b881df09fdecf569c8b142b27fc989638720aeda2813f82442b6e3d91b') -print(dig) - -if dig != '59e332b881df09fdecf569c8b142b27fc989638720aeda2813f82442b6e3d91b': - raise Exception("Error") - -dig = hmac.new(key[:32], msg=msg, digestmod=sha256).hexdigest() - -print('b72fed815cd71acfa3a2f5cf2343679565fa18e7cd92226ab443aabd1fd7b7b0') -print(dig) - -if dig != 'b72fed815cd71acfa3a2f5cf2343679565fa18e7cd92226ab443aabd1fd7b7b0': - raise Exception("Error") - -dig = hmac.new(key, msg=msg, digestmod=sha256).hexdigest() - -print('4e51beae6c2b0f90bb3e99d8e93a32d168b6c1e9b7d2130e2d668a3b3e10358d') -print(dig) - -if dig != '4e51beae6c2b0f90bb3e99d8e93a32d168b6c1e9b7d2130e2d668a3b3e10358d': - raise Exception("Error") - diff --git a/html.entities/html/entities.py b/html.entities/html/entities.py deleted file mode 100644 index e891ad659..000000000 --- a/html.entities/html/entities.py +++ /dev/null @@ -1,2506 +0,0 @@ -"""HTML character entity references.""" - -# maps the HTML entity name to the Unicode codepoint -name2codepoint = { - 'AElig': 0x00c6, # latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1 - 'Aacute': 0x00c1, # latin capital letter A with acute, U+00C1 ISOlat1 - 'Acirc': 0x00c2, # latin capital letter A with circumflex, U+00C2 ISOlat1 - 'Agrave': 0x00c0, # latin capital letter A with grave = latin capital letter A grave, U+00C0 ISOlat1 - 'Alpha': 0x0391, # greek capital letter alpha, U+0391 - 'Aring': 0x00c5, # latin capital letter A with ring above = latin capital letter A ring, U+00C5 ISOlat1 - 'Atilde': 0x00c3, # latin capital letter A with tilde, U+00C3 ISOlat1 - 'Auml': 0x00c4, # latin capital letter A with diaeresis, U+00C4 ISOlat1 - 'Beta': 0x0392, # greek capital letter beta, U+0392 - 'Ccedil': 0x00c7, # latin capital letter C with cedilla, U+00C7 ISOlat1 - 'Chi': 0x03a7, # greek capital letter chi, U+03A7 - 'Dagger': 0x2021, # double dagger, U+2021 ISOpub - 'Delta': 0x0394, # greek capital letter delta, U+0394 ISOgrk3 - 'ETH': 0x00d0, # latin capital letter ETH, U+00D0 ISOlat1 - 'Eacute': 0x00c9, # latin capital letter E with acute, U+00C9 ISOlat1 - 'Ecirc': 0x00ca, # latin capital letter E with circumflex, U+00CA ISOlat1 - 'Egrave': 0x00c8, # latin capital letter E with grave, U+00C8 ISOlat1 - 'Epsilon': 0x0395, # greek capital letter epsilon, U+0395 - 'Eta': 0x0397, # greek capital letter eta, U+0397 - 'Euml': 0x00cb, # latin capital letter E with diaeresis, U+00CB ISOlat1 - 'Gamma': 0x0393, # greek capital letter gamma, U+0393 ISOgrk3 - 'Iacute': 0x00cd, # latin capital letter I with acute, U+00CD ISOlat1 - 'Icirc': 0x00ce, # latin capital letter I with circumflex, U+00CE ISOlat1 - 'Igrave': 0x00cc, # latin capital letter I with grave, U+00CC ISOlat1 - 'Iota': 0x0399, # greek capital letter iota, U+0399 - 'Iuml': 0x00cf, # latin capital letter I with diaeresis, U+00CF ISOlat1 - 'Kappa': 0x039a, # greek capital letter kappa, U+039A - 'Lambda': 0x039b, # greek capital letter lambda, U+039B ISOgrk3 - 'Mu': 0x039c, # greek capital letter mu, U+039C - 'Ntilde': 0x00d1, # latin capital letter N with tilde, U+00D1 ISOlat1 - 'Nu': 0x039d, # greek capital letter nu, U+039D - 'OElig': 0x0152, # latin capital ligature OE, U+0152 ISOlat2 - 'Oacute': 0x00d3, # latin capital letter O with acute, U+00D3 ISOlat1 - 'Ocirc': 0x00d4, # latin capital letter O with circumflex, U+00D4 ISOlat1 - 'Ograve': 0x00d2, # latin capital letter O with grave, U+00D2 ISOlat1 - 'Omega': 0x03a9, # greek capital letter omega, U+03A9 ISOgrk3 - 'Omicron': 0x039f, # greek capital letter omicron, U+039F - 'Oslash': 0x00d8, # latin capital letter O with stroke = latin capital letter O slash, U+00D8 ISOlat1 - 'Otilde': 0x00d5, # latin capital letter O with tilde, U+00D5 ISOlat1 - 'Ouml': 0x00d6, # latin capital letter O with diaeresis, U+00D6 ISOlat1 - 'Phi': 0x03a6, # greek capital letter phi, U+03A6 ISOgrk3 - 'Pi': 0x03a0, # greek capital letter pi, U+03A0 ISOgrk3 - 'Prime': 0x2033, # double prime = seconds = inches, U+2033 ISOtech - 'Psi': 0x03a8, # greek capital letter psi, U+03A8 ISOgrk3 - 'Rho': 0x03a1, # greek capital letter rho, U+03A1 - 'Scaron': 0x0160, # latin capital letter S with caron, U+0160 ISOlat2 - 'Sigma': 0x03a3, # greek capital letter sigma, U+03A3 ISOgrk3 - 'THORN': 0x00de, # latin capital letter THORN, U+00DE ISOlat1 - 'Tau': 0x03a4, # greek capital letter tau, U+03A4 - 'Theta': 0x0398, # greek capital letter theta, U+0398 ISOgrk3 - 'Uacute': 0x00da, # latin capital letter U with acute, U+00DA ISOlat1 - 'Ucirc': 0x00db, # latin capital letter U with circumflex, U+00DB ISOlat1 - 'Ugrave': 0x00d9, # latin capital letter U with grave, U+00D9 ISOlat1 - 'Upsilon': 0x03a5, # greek capital letter upsilon, U+03A5 ISOgrk3 - 'Uuml': 0x00dc, # latin capital letter U with diaeresis, U+00DC ISOlat1 - 'Xi': 0x039e, # greek capital letter xi, U+039E ISOgrk3 - 'Yacute': 0x00dd, # latin capital letter Y with acute, U+00DD ISOlat1 - 'Yuml': 0x0178, # latin capital letter Y with diaeresis, U+0178 ISOlat2 - 'Zeta': 0x0396, # greek capital letter zeta, U+0396 - 'aacute': 0x00e1, # latin small letter a with acute, U+00E1 ISOlat1 - 'acirc': 0x00e2, # latin small letter a with circumflex, U+00E2 ISOlat1 - 'acute': 0x00b4, # acute accent = spacing acute, U+00B4 ISOdia - 'aelig': 0x00e6, # latin small letter ae = latin small ligature ae, U+00E6 ISOlat1 - 'agrave': 0x00e0, # latin small letter a with grave = latin small letter a grave, U+00E0 ISOlat1 - 'alefsym': 0x2135, # alef symbol = first transfinite cardinal, U+2135 NEW - 'alpha': 0x03b1, # greek small letter alpha, U+03B1 ISOgrk3 - 'amp': 0x0026, # ampersand, U+0026 ISOnum - 'and': 0x2227, # logical and = wedge, U+2227 ISOtech - 'ang': 0x2220, # angle, U+2220 ISOamso - 'aring': 0x00e5, # latin small letter a with ring above = latin small letter a ring, U+00E5 ISOlat1 - 'asymp': 0x2248, # almost equal to = asymptotic to, U+2248 ISOamsr - 'atilde': 0x00e3, # latin small letter a with tilde, U+00E3 ISOlat1 - 'auml': 0x00e4, # latin small letter a with diaeresis, U+00E4 ISOlat1 - 'bdquo': 0x201e, # double low-9 quotation mark, U+201E NEW - 'beta': 0x03b2, # greek small letter beta, U+03B2 ISOgrk3 - 'brvbar': 0x00a6, # broken bar = broken vertical bar, U+00A6 ISOnum - 'bull': 0x2022, # bullet = black small circle, U+2022 ISOpub - 'cap': 0x2229, # intersection = cap, U+2229 ISOtech - 'ccedil': 0x00e7, # latin small letter c with cedilla, U+00E7 ISOlat1 - 'cedil': 0x00b8, # cedilla = spacing cedilla, U+00B8 ISOdia - 'cent': 0x00a2, # cent sign, U+00A2 ISOnum - 'chi': 0x03c7, # greek small letter chi, U+03C7 ISOgrk3 - 'circ': 0x02c6, # modifier letter circumflex accent, U+02C6 ISOpub - 'clubs': 0x2663, # black club suit = shamrock, U+2663 ISOpub - 'cong': 0x2245, # approximately equal to, U+2245 ISOtech - 'copy': 0x00a9, # copyright sign, U+00A9 ISOnum - 'crarr': 0x21b5, # downwards arrow with corner leftwards = carriage return, U+21B5 NEW - 'cup': 0x222a, # union = cup, U+222A ISOtech - 'curren': 0x00a4, # currency sign, U+00A4 ISOnum - 'dArr': 0x21d3, # downwards double arrow, U+21D3 ISOamsa - 'dagger': 0x2020, # dagger, U+2020 ISOpub - 'darr': 0x2193, # downwards arrow, U+2193 ISOnum - 'deg': 0x00b0, # degree sign, U+00B0 ISOnum - 'delta': 0x03b4, # greek small letter delta, U+03B4 ISOgrk3 - 'diams': 0x2666, # black diamond suit, U+2666 ISOpub - 'divide': 0x00f7, # division sign, U+00F7 ISOnum - 'eacute': 0x00e9, # latin small letter e with acute, U+00E9 ISOlat1 - 'ecirc': 0x00ea, # latin small letter e with circumflex, U+00EA ISOlat1 - 'egrave': 0x00e8, # latin small letter e with grave, U+00E8 ISOlat1 - 'empty': 0x2205, # empty set = null set = diameter, U+2205 ISOamso - 'emsp': 0x2003, # em space, U+2003 ISOpub - 'ensp': 0x2002, # en space, U+2002 ISOpub - 'epsilon': 0x03b5, # greek small letter epsilon, U+03B5 ISOgrk3 - 'equiv': 0x2261, # identical to, U+2261 ISOtech - 'eta': 0x03b7, # greek small letter eta, U+03B7 ISOgrk3 - 'eth': 0x00f0, # latin small letter eth, U+00F0 ISOlat1 - 'euml': 0x00eb, # latin small letter e with diaeresis, U+00EB ISOlat1 - 'euro': 0x20ac, # euro sign, U+20AC NEW - 'exist': 0x2203, # there exists, U+2203 ISOtech - 'fnof': 0x0192, # latin small f with hook = function = florin, U+0192 ISOtech - 'forall': 0x2200, # for all, U+2200 ISOtech - 'frac12': 0x00bd, # vulgar fraction one half = fraction one half, U+00BD ISOnum - 'frac14': 0x00bc, # vulgar fraction one quarter = fraction one quarter, U+00BC ISOnum - 'frac34': 0x00be, # vulgar fraction three quarters = fraction three quarters, U+00BE ISOnum - 'frasl': 0x2044, # fraction slash, U+2044 NEW - 'gamma': 0x03b3, # greek small letter gamma, U+03B3 ISOgrk3 - 'ge': 0x2265, # greater-than or equal to, U+2265 ISOtech - 'gt': 0x003e, # greater-than sign, U+003E ISOnum - 'hArr': 0x21d4, # left right double arrow, U+21D4 ISOamsa - 'harr': 0x2194, # left right arrow, U+2194 ISOamsa - 'hearts': 0x2665, # black heart suit = valentine, U+2665 ISOpub - 'hellip': 0x2026, # horizontal ellipsis = three dot leader, U+2026 ISOpub - 'iacute': 0x00ed, # latin small letter i with acute, U+00ED ISOlat1 - 'icirc': 0x00ee, # latin small letter i with circumflex, U+00EE ISOlat1 - 'iexcl': 0x00a1, # inverted exclamation mark, U+00A1 ISOnum - 'igrave': 0x00ec, # latin small letter i with grave, U+00EC ISOlat1 - 'image': 0x2111, # blackletter capital I = imaginary part, U+2111 ISOamso - 'infin': 0x221e, # infinity, U+221E ISOtech - 'int': 0x222b, # integral, U+222B ISOtech - 'iota': 0x03b9, # greek small letter iota, U+03B9 ISOgrk3 - 'iquest': 0x00bf, # inverted question mark = turned question mark, U+00BF ISOnum - 'isin': 0x2208, # element of, U+2208 ISOtech - 'iuml': 0x00ef, # latin small letter i with diaeresis, U+00EF ISOlat1 - 'kappa': 0x03ba, # greek small letter kappa, U+03BA ISOgrk3 - 'lArr': 0x21d0, # leftwards double arrow, U+21D0 ISOtech - 'lambda': 0x03bb, # greek small letter lambda, U+03BB ISOgrk3 - 'lang': 0x2329, # left-pointing angle bracket = bra, U+2329 ISOtech - 'laquo': 0x00ab, # left-pointing double angle quotation mark = left pointing guillemet, U+00AB ISOnum - 'larr': 0x2190, # leftwards arrow, U+2190 ISOnum - 'lceil': 0x2308, # left ceiling = apl upstile, U+2308 ISOamsc - 'ldquo': 0x201c, # left double quotation mark, U+201C ISOnum - 'le': 0x2264, # less-than or equal to, U+2264 ISOtech - 'lfloor': 0x230a, # left floor = apl downstile, U+230A ISOamsc - 'lowast': 0x2217, # asterisk operator, U+2217 ISOtech - 'loz': 0x25ca, # lozenge, U+25CA ISOpub - 'lrm': 0x200e, # left-to-right mark, U+200E NEW RFC 2070 - 'lsaquo': 0x2039, # single left-pointing angle quotation mark, U+2039 ISO proposed - 'lsquo': 0x2018, # left single quotation mark, U+2018 ISOnum - 'lt': 0x003c, # less-than sign, U+003C ISOnum - 'macr': 0x00af, # macron = spacing macron = overline = APL overbar, U+00AF ISOdia - 'mdash': 0x2014, # em dash, U+2014 ISOpub - 'micro': 0x00b5, # micro sign, U+00B5 ISOnum - 'middot': 0x00b7, # middle dot = Georgian comma = Greek middle dot, U+00B7 ISOnum - 'minus': 0x2212, # minus sign, U+2212 ISOtech - 'mu': 0x03bc, # greek small letter mu, U+03BC ISOgrk3 - 'nabla': 0x2207, # nabla = backward difference, U+2207 ISOtech - 'nbsp': 0x00a0, # no-break space = non-breaking space, U+00A0 ISOnum - 'ndash': 0x2013, # en dash, U+2013 ISOpub - 'ne': 0x2260, # not equal to, U+2260 ISOtech - 'ni': 0x220b, # contains as member, U+220B ISOtech - 'not': 0x00ac, # not sign, U+00AC ISOnum - 'notin': 0x2209, # not an element of, U+2209 ISOtech - 'nsub': 0x2284, # not a subset of, U+2284 ISOamsn - 'ntilde': 0x00f1, # latin small letter n with tilde, U+00F1 ISOlat1 - 'nu': 0x03bd, # greek small letter nu, U+03BD ISOgrk3 - 'oacute': 0x00f3, # latin small letter o with acute, U+00F3 ISOlat1 - 'ocirc': 0x00f4, # latin small letter o with circumflex, U+00F4 ISOlat1 - 'oelig': 0x0153, # latin small ligature oe, U+0153 ISOlat2 - 'ograve': 0x00f2, # latin small letter o with grave, U+00F2 ISOlat1 - 'oline': 0x203e, # overline = spacing overscore, U+203E NEW - 'omega': 0x03c9, # greek small letter omega, U+03C9 ISOgrk3 - 'omicron': 0x03bf, # greek small letter omicron, U+03BF NEW - 'oplus': 0x2295, # circled plus = direct sum, U+2295 ISOamsb - 'or': 0x2228, # logical or = vee, U+2228 ISOtech - 'ordf': 0x00aa, # feminine ordinal indicator, U+00AA ISOnum - 'ordm': 0x00ba, # masculine ordinal indicator, U+00BA ISOnum - 'oslash': 0x00f8, # latin small letter o with stroke, = latin small letter o slash, U+00F8 ISOlat1 - 'otilde': 0x00f5, # latin small letter o with tilde, U+00F5 ISOlat1 - 'otimes': 0x2297, # circled times = vector product, U+2297 ISOamsb - 'ouml': 0x00f6, # latin small letter o with diaeresis, U+00F6 ISOlat1 - 'para': 0x00b6, # pilcrow sign = paragraph sign, U+00B6 ISOnum - 'part': 0x2202, # partial differential, U+2202 ISOtech - 'permil': 0x2030, # per mille sign, U+2030 ISOtech - 'perp': 0x22a5, # up tack = orthogonal to = perpendicular, U+22A5 ISOtech - 'phi': 0x03c6, # greek small letter phi, U+03C6 ISOgrk3 - 'pi': 0x03c0, # greek small letter pi, U+03C0 ISOgrk3 - 'piv': 0x03d6, # greek pi symbol, U+03D6 ISOgrk3 - 'plusmn': 0x00b1, # plus-minus sign = plus-or-minus sign, U+00B1 ISOnum - 'pound': 0x00a3, # pound sign, U+00A3 ISOnum - 'prime': 0x2032, # prime = minutes = feet, U+2032 ISOtech - 'prod': 0x220f, # n-ary product = product sign, U+220F ISOamsb - 'prop': 0x221d, # proportional to, U+221D ISOtech - 'psi': 0x03c8, # greek small letter psi, U+03C8 ISOgrk3 - 'quot': 0x0022, # quotation mark = APL quote, U+0022 ISOnum - 'rArr': 0x21d2, # rightwards double arrow, U+21D2 ISOtech - 'radic': 0x221a, # square root = radical sign, U+221A ISOtech - 'rang': 0x232a, # right-pointing angle bracket = ket, U+232A ISOtech - 'raquo': 0x00bb, # right-pointing double angle quotation mark = right pointing guillemet, U+00BB ISOnum - 'rarr': 0x2192, # rightwards arrow, U+2192 ISOnum - 'rceil': 0x2309, # right ceiling, U+2309 ISOamsc - 'rdquo': 0x201d, # right double quotation mark, U+201D ISOnum - 'real': 0x211c, # blackletter capital R = real part symbol, U+211C ISOamso - 'reg': 0x00ae, # registered sign = registered trade mark sign, U+00AE ISOnum - 'rfloor': 0x230b, # right floor, U+230B ISOamsc - 'rho': 0x03c1, # greek small letter rho, U+03C1 ISOgrk3 - 'rlm': 0x200f, # right-to-left mark, U+200F NEW RFC 2070 - 'rsaquo': 0x203a, # single right-pointing angle quotation mark, U+203A ISO proposed - 'rsquo': 0x2019, # right single quotation mark, U+2019 ISOnum - 'sbquo': 0x201a, # single low-9 quotation mark, U+201A NEW - 'scaron': 0x0161, # latin small letter s with caron, U+0161 ISOlat2 - 'sdot': 0x22c5, # dot operator, U+22C5 ISOamsb - 'sect': 0x00a7, # section sign, U+00A7 ISOnum - 'shy': 0x00ad, # soft hyphen = discretionary hyphen, U+00AD ISOnum - 'sigma': 0x03c3, # greek small letter sigma, U+03C3 ISOgrk3 - 'sigmaf': 0x03c2, # greek small letter final sigma, U+03C2 ISOgrk3 - 'sim': 0x223c, # tilde operator = varies with = similar to, U+223C ISOtech - 'spades': 0x2660, # black spade suit, U+2660 ISOpub - 'sub': 0x2282, # subset of, U+2282 ISOtech - 'sube': 0x2286, # subset of or equal to, U+2286 ISOtech - 'sum': 0x2211, # n-ary sumation, U+2211 ISOamsb - 'sup': 0x2283, # superset of, U+2283 ISOtech - 'sup1': 0x00b9, # superscript one = superscript digit one, U+00B9 ISOnum - 'sup2': 0x00b2, # superscript two = superscript digit two = squared, U+00B2 ISOnum - 'sup3': 0x00b3, # superscript three = superscript digit three = cubed, U+00B3 ISOnum - 'supe': 0x2287, # superset of or equal to, U+2287 ISOtech - 'szlig': 0x00df, # latin small letter sharp s = ess-zed, U+00DF ISOlat1 - 'tau': 0x03c4, # greek small letter tau, U+03C4 ISOgrk3 - 'there4': 0x2234, # therefore, U+2234 ISOtech - 'theta': 0x03b8, # greek small letter theta, U+03B8 ISOgrk3 - 'thetasym': 0x03d1, # greek small letter theta symbol, U+03D1 NEW - 'thinsp': 0x2009, # thin space, U+2009 ISOpub - 'thorn': 0x00fe, # latin small letter thorn with, U+00FE ISOlat1 - 'tilde': 0x02dc, # small tilde, U+02DC ISOdia - 'times': 0x00d7, # multiplication sign, U+00D7 ISOnum - 'trade': 0x2122, # trade mark sign, U+2122 ISOnum - 'uArr': 0x21d1, # upwards double arrow, U+21D1 ISOamsa - 'uacute': 0x00fa, # latin small letter u with acute, U+00FA ISOlat1 - 'uarr': 0x2191, # upwards arrow, U+2191 ISOnum - 'ucirc': 0x00fb, # latin small letter u with circumflex, U+00FB ISOlat1 - 'ugrave': 0x00f9, # latin small letter u with grave, U+00F9 ISOlat1 - 'uml': 0x00a8, # diaeresis = spacing diaeresis, U+00A8 ISOdia - 'upsih': 0x03d2, # greek upsilon with hook symbol, U+03D2 NEW - 'upsilon': 0x03c5, # greek small letter upsilon, U+03C5 ISOgrk3 - 'uuml': 0x00fc, # latin small letter u with diaeresis, U+00FC ISOlat1 - 'weierp': 0x2118, # script capital P = power set = Weierstrass p, U+2118 ISOamso - 'xi': 0x03be, # greek small letter xi, U+03BE ISOgrk3 - 'yacute': 0x00fd, # latin small letter y with acute, U+00FD ISOlat1 - 'yen': 0x00a5, # yen sign = yuan sign, U+00A5 ISOnum - 'yuml': 0x00ff, # latin small letter y with diaeresis, U+00FF ISOlat1 - 'zeta': 0x03b6, # greek small letter zeta, U+03B6 ISOgrk3 - 'zwj': 0x200d, # zero width joiner, U+200D NEW RFC 2070 - 'zwnj': 0x200c, # zero width non-joiner, U+200C NEW RFC 2070 -} - - -# maps the HTML5 named character references to the equivalent Unicode character(s) -html5 = { - 'Aacute': '\xc1', - 'aacute': '\xe1', - 'Aacute;': '\xc1', - 'aacute;': '\xe1', - 'Abreve;': '\u0102', - 'abreve;': '\u0103', - 'ac;': '\u223e', - 'acd;': '\u223f', - 'acE;': '\u223e\u0333', - 'Acirc': '\xc2', - 'acirc': '\xe2', - 'Acirc;': '\xc2', - 'acirc;': '\xe2', - 'acute': '\xb4', - 'acute;': '\xb4', - 'Acy;': '\u0410', - 'acy;': '\u0430', - 'AElig': '\xc6', - 'aelig': '\xe6', - 'AElig;': '\xc6', - 'aelig;': '\xe6', - 'af;': '\u2061', - 'Afr;': '\U0001d504', - 'afr;': '\U0001d51e', - 'Agrave': '\xc0', - 'agrave': '\xe0', - 'Agrave;': '\xc0', - 'agrave;': '\xe0', - 'alefsym;': '\u2135', - 'aleph;': '\u2135', - 'Alpha;': '\u0391', - 'alpha;': '\u03b1', - 'Amacr;': '\u0100', - 'amacr;': '\u0101', - 'amalg;': '\u2a3f', - 'AMP': '&', - 'amp': '&', - 'AMP;': '&', - 'amp;': '&', - 'And;': '\u2a53', - 'and;': '\u2227', - 'andand;': '\u2a55', - 'andd;': '\u2a5c', - 'andslope;': '\u2a58', - 'andv;': '\u2a5a', - 'ang;': '\u2220', - 'ange;': '\u29a4', - 'angle;': '\u2220', - 'angmsd;': '\u2221', - 'angmsdaa;': '\u29a8', - 'angmsdab;': '\u29a9', - 'angmsdac;': '\u29aa', - 'angmsdad;': '\u29ab', - 'angmsdae;': '\u29ac', - 'angmsdaf;': '\u29ad', - 'angmsdag;': '\u29ae', - 'angmsdah;': '\u29af', - 'angrt;': '\u221f', - 'angrtvb;': '\u22be', - 'angrtvbd;': '\u299d', - 'angsph;': '\u2222', - 'angst;': '\xc5', - 'angzarr;': '\u237c', - 'Aogon;': '\u0104', - 'aogon;': '\u0105', - 'Aopf;': '\U0001d538', - 'aopf;': '\U0001d552', - 'ap;': '\u2248', - 'apacir;': '\u2a6f', - 'apE;': '\u2a70', - 'ape;': '\u224a', - 'apid;': '\u224b', - 'apos;': "'", - 'ApplyFunction;': '\u2061', - 'approx;': '\u2248', - 'approxeq;': '\u224a', - 'Aring': '\xc5', - 'aring': '\xe5', - 'Aring;': '\xc5', - 'aring;': '\xe5', - 'Ascr;': '\U0001d49c', - 'ascr;': '\U0001d4b6', - 'Assign;': '\u2254', - 'ast;': '*', - 'asymp;': '\u2248', - 'asympeq;': '\u224d', - 'Atilde': '\xc3', - 'atilde': '\xe3', - 'Atilde;': '\xc3', - 'atilde;': '\xe3', - 'Auml': '\xc4', - 'auml': '\xe4', - 'Auml;': '\xc4', - 'auml;': '\xe4', - 'awconint;': '\u2233', - 'awint;': '\u2a11', - 'backcong;': '\u224c', - 'backepsilon;': '\u03f6', - 'backprime;': '\u2035', - 'backsim;': '\u223d', - 'backsimeq;': '\u22cd', - 'Backslash;': '\u2216', - 'Barv;': '\u2ae7', - 'barvee;': '\u22bd', - 'Barwed;': '\u2306', - 'barwed;': '\u2305', - 'barwedge;': '\u2305', - 'bbrk;': '\u23b5', - 'bbrktbrk;': '\u23b6', - 'bcong;': '\u224c', - 'Bcy;': '\u0411', - 'bcy;': '\u0431', - 'bdquo;': '\u201e', - 'becaus;': '\u2235', - 'Because;': '\u2235', - 'because;': '\u2235', - 'bemptyv;': '\u29b0', - 'bepsi;': '\u03f6', - 'bernou;': '\u212c', - 'Bernoullis;': '\u212c', - 'Beta;': '\u0392', - 'beta;': '\u03b2', - 'beth;': '\u2136', - 'between;': '\u226c', - 'Bfr;': '\U0001d505', - 'bfr;': '\U0001d51f', - 'bigcap;': '\u22c2', - 'bigcirc;': '\u25ef', - 'bigcup;': '\u22c3', - 'bigodot;': '\u2a00', - 'bigoplus;': '\u2a01', - 'bigotimes;': '\u2a02', - 'bigsqcup;': '\u2a06', - 'bigstar;': '\u2605', - 'bigtriangledown;': '\u25bd', - 'bigtriangleup;': '\u25b3', - 'biguplus;': '\u2a04', - 'bigvee;': '\u22c1', - 'bigwedge;': '\u22c0', - 'bkarow;': '\u290d', - 'blacklozenge;': '\u29eb', - 'blacksquare;': '\u25aa', - 'blacktriangle;': '\u25b4', - 'blacktriangledown;': '\u25be', - 'blacktriangleleft;': '\u25c2', - 'blacktriangleright;': '\u25b8', - 'blank;': '\u2423', - 'blk12;': '\u2592', - 'blk14;': '\u2591', - 'blk34;': '\u2593', - 'block;': '\u2588', - 'bne;': '=\u20e5', - 'bnequiv;': '\u2261\u20e5', - 'bNot;': '\u2aed', - 'bnot;': '\u2310', - 'Bopf;': '\U0001d539', - 'bopf;': '\U0001d553', - 'bot;': '\u22a5', - 'bottom;': '\u22a5', - 'bowtie;': '\u22c8', - 'boxbox;': '\u29c9', - 'boxDL;': '\u2557', - 'boxDl;': '\u2556', - 'boxdL;': '\u2555', - 'boxdl;': '\u2510', - 'boxDR;': '\u2554', - 'boxDr;': '\u2553', - 'boxdR;': '\u2552', - 'boxdr;': '\u250c', - 'boxH;': '\u2550', - 'boxh;': '\u2500', - 'boxHD;': '\u2566', - 'boxHd;': '\u2564', - 'boxhD;': '\u2565', - 'boxhd;': '\u252c', - 'boxHU;': '\u2569', - 'boxHu;': '\u2567', - 'boxhU;': '\u2568', - 'boxhu;': '\u2534', - 'boxminus;': '\u229f', - 'boxplus;': '\u229e', - 'boxtimes;': '\u22a0', - 'boxUL;': '\u255d', - 'boxUl;': '\u255c', - 'boxuL;': '\u255b', - 'boxul;': '\u2518', - 'boxUR;': '\u255a', - 'boxUr;': '\u2559', - 'boxuR;': '\u2558', - 'boxur;': '\u2514', - 'boxV;': '\u2551', - 'boxv;': '\u2502', - 'boxVH;': '\u256c', - 'boxVh;': '\u256b', - 'boxvH;': '\u256a', - 'boxvh;': '\u253c', - 'boxVL;': '\u2563', - 'boxVl;': '\u2562', - 'boxvL;': '\u2561', - 'boxvl;': '\u2524', - 'boxVR;': '\u2560', - 'boxVr;': '\u255f', - 'boxvR;': '\u255e', - 'boxvr;': '\u251c', - 'bprime;': '\u2035', - 'Breve;': '\u02d8', - 'breve;': '\u02d8', - 'brvbar': '\xa6', - 'brvbar;': '\xa6', - 'Bscr;': '\u212c', - 'bscr;': '\U0001d4b7', - 'bsemi;': '\u204f', - 'bsim;': '\u223d', - 'bsime;': '\u22cd', - 'bsol;': '\\', - 'bsolb;': '\u29c5', - 'bsolhsub;': '\u27c8', - 'bull;': '\u2022', - 'bullet;': '\u2022', - 'bump;': '\u224e', - 'bumpE;': '\u2aae', - 'bumpe;': '\u224f', - 'Bumpeq;': '\u224e', - 'bumpeq;': '\u224f', - 'Cacute;': '\u0106', - 'cacute;': '\u0107', - 'Cap;': '\u22d2', - 'cap;': '\u2229', - 'capand;': '\u2a44', - 'capbrcup;': '\u2a49', - 'capcap;': '\u2a4b', - 'capcup;': '\u2a47', - 'capdot;': '\u2a40', - 'CapitalDifferentialD;': '\u2145', - 'caps;': '\u2229\ufe00', - 'caret;': '\u2041', - 'caron;': '\u02c7', - 'Cayleys;': '\u212d', - 'ccaps;': '\u2a4d', - 'Ccaron;': '\u010c', - 'ccaron;': '\u010d', - 'Ccedil': '\xc7', - 'ccedil': '\xe7', - 'Ccedil;': '\xc7', - 'ccedil;': '\xe7', - 'Ccirc;': '\u0108', - 'ccirc;': '\u0109', - 'Cconint;': '\u2230', - 'ccups;': '\u2a4c', - 'ccupssm;': '\u2a50', - 'Cdot;': '\u010a', - 'cdot;': '\u010b', - 'cedil': '\xb8', - 'cedil;': '\xb8', - 'Cedilla;': '\xb8', - 'cemptyv;': '\u29b2', - 'cent': '\xa2', - 'cent;': '\xa2', - 'CenterDot;': '\xb7', - 'centerdot;': '\xb7', - 'Cfr;': '\u212d', - 'cfr;': '\U0001d520', - 'CHcy;': '\u0427', - 'chcy;': '\u0447', - 'check;': '\u2713', - 'checkmark;': '\u2713', - 'Chi;': '\u03a7', - 'chi;': '\u03c7', - 'cir;': '\u25cb', - 'circ;': '\u02c6', - 'circeq;': '\u2257', - 'circlearrowleft;': '\u21ba', - 'circlearrowright;': '\u21bb', - 'circledast;': '\u229b', - 'circledcirc;': '\u229a', - 'circleddash;': '\u229d', - 'CircleDot;': '\u2299', - 'circledR;': '\xae', - 'circledS;': '\u24c8', - 'CircleMinus;': '\u2296', - 'CirclePlus;': '\u2295', - 'CircleTimes;': '\u2297', - 'cirE;': '\u29c3', - 'cire;': '\u2257', - 'cirfnint;': '\u2a10', - 'cirmid;': '\u2aef', - 'cirscir;': '\u29c2', - 'ClockwiseContourIntegral;': '\u2232', - 'CloseCurlyDoubleQuote;': '\u201d', - 'CloseCurlyQuote;': '\u2019', - 'clubs;': '\u2663', - 'clubsuit;': '\u2663', - 'Colon;': '\u2237', - 'colon;': ':', - 'Colone;': '\u2a74', - 'colone;': '\u2254', - 'coloneq;': '\u2254', - 'comma;': ',', - 'commat;': '@', - 'comp;': '\u2201', - 'compfn;': '\u2218', - 'complement;': '\u2201', - 'complexes;': '\u2102', - 'cong;': '\u2245', - 'congdot;': '\u2a6d', - 'Congruent;': '\u2261', - 'Conint;': '\u222f', - 'conint;': '\u222e', - 'ContourIntegral;': '\u222e', - 'Copf;': '\u2102', - 'copf;': '\U0001d554', - 'coprod;': '\u2210', - 'Coproduct;': '\u2210', - 'COPY': '\xa9', - 'copy': '\xa9', - 'COPY;': '\xa9', - 'copy;': '\xa9', - 'copysr;': '\u2117', - 'CounterClockwiseContourIntegral;': '\u2233', - 'crarr;': '\u21b5', - 'Cross;': '\u2a2f', - 'cross;': '\u2717', - 'Cscr;': '\U0001d49e', - 'cscr;': '\U0001d4b8', - 'csub;': '\u2acf', - 'csube;': '\u2ad1', - 'csup;': '\u2ad0', - 'csupe;': '\u2ad2', - 'ctdot;': '\u22ef', - 'cudarrl;': '\u2938', - 'cudarrr;': '\u2935', - 'cuepr;': '\u22de', - 'cuesc;': '\u22df', - 'cularr;': '\u21b6', - 'cularrp;': '\u293d', - 'Cup;': '\u22d3', - 'cup;': '\u222a', - 'cupbrcap;': '\u2a48', - 'CupCap;': '\u224d', - 'cupcap;': '\u2a46', - 'cupcup;': '\u2a4a', - 'cupdot;': '\u228d', - 'cupor;': '\u2a45', - 'cups;': '\u222a\ufe00', - 'curarr;': '\u21b7', - 'curarrm;': '\u293c', - 'curlyeqprec;': '\u22de', - 'curlyeqsucc;': '\u22df', - 'curlyvee;': '\u22ce', - 'curlywedge;': '\u22cf', - 'curren': '\xa4', - 'curren;': '\xa4', - 'curvearrowleft;': '\u21b6', - 'curvearrowright;': '\u21b7', - 'cuvee;': '\u22ce', - 'cuwed;': '\u22cf', - 'cwconint;': '\u2232', - 'cwint;': '\u2231', - 'cylcty;': '\u232d', - 'Dagger;': '\u2021', - 'dagger;': '\u2020', - 'daleth;': '\u2138', - 'Darr;': '\u21a1', - 'dArr;': '\u21d3', - 'darr;': '\u2193', - 'dash;': '\u2010', - 'Dashv;': '\u2ae4', - 'dashv;': '\u22a3', - 'dbkarow;': '\u290f', - 'dblac;': '\u02dd', - 'Dcaron;': '\u010e', - 'dcaron;': '\u010f', - 'Dcy;': '\u0414', - 'dcy;': '\u0434', - 'DD;': '\u2145', - 'dd;': '\u2146', - 'ddagger;': '\u2021', - 'ddarr;': '\u21ca', - 'DDotrahd;': '\u2911', - 'ddotseq;': '\u2a77', - 'deg': '\xb0', - 'deg;': '\xb0', - 'Del;': '\u2207', - 'Delta;': '\u0394', - 'delta;': '\u03b4', - 'demptyv;': '\u29b1', - 'dfisht;': '\u297f', - 'Dfr;': '\U0001d507', - 'dfr;': '\U0001d521', - 'dHar;': '\u2965', - 'dharl;': '\u21c3', - 'dharr;': '\u21c2', - 'DiacriticalAcute;': '\xb4', - 'DiacriticalDot;': '\u02d9', - 'DiacriticalDoubleAcute;': '\u02dd', - 'DiacriticalGrave;': '`', - 'DiacriticalTilde;': '\u02dc', - 'diam;': '\u22c4', - 'Diamond;': '\u22c4', - 'diamond;': '\u22c4', - 'diamondsuit;': '\u2666', - 'diams;': '\u2666', - 'die;': '\xa8', - 'DifferentialD;': '\u2146', - 'digamma;': '\u03dd', - 'disin;': '\u22f2', - 'div;': '\xf7', - 'divide': '\xf7', - 'divide;': '\xf7', - 'divideontimes;': '\u22c7', - 'divonx;': '\u22c7', - 'DJcy;': '\u0402', - 'djcy;': '\u0452', - 'dlcorn;': '\u231e', - 'dlcrop;': '\u230d', - 'dollar;': '$', - 'Dopf;': '\U0001d53b', - 'dopf;': '\U0001d555', - 'Dot;': '\xa8', - 'dot;': '\u02d9', - 'DotDot;': '\u20dc', - 'doteq;': '\u2250', - 'doteqdot;': '\u2251', - 'DotEqual;': '\u2250', - 'dotminus;': '\u2238', - 'dotplus;': '\u2214', - 'dotsquare;': '\u22a1', - 'doublebarwedge;': '\u2306', - 'DoubleContourIntegral;': '\u222f', - 'DoubleDot;': '\xa8', - 'DoubleDownArrow;': '\u21d3', - 'DoubleLeftArrow;': '\u21d0', - 'DoubleLeftRightArrow;': '\u21d4', - 'DoubleLeftTee;': '\u2ae4', - 'DoubleLongLeftArrow;': '\u27f8', - 'DoubleLongLeftRightArrow;': '\u27fa', - 'DoubleLongRightArrow;': '\u27f9', - 'DoubleRightArrow;': '\u21d2', - 'DoubleRightTee;': '\u22a8', - 'DoubleUpArrow;': '\u21d1', - 'DoubleUpDownArrow;': '\u21d5', - 'DoubleVerticalBar;': '\u2225', - 'DownArrow;': '\u2193', - 'Downarrow;': '\u21d3', - 'downarrow;': '\u2193', - 'DownArrowBar;': '\u2913', - 'DownArrowUpArrow;': '\u21f5', - 'DownBreve;': '\u0311', - 'downdownarrows;': '\u21ca', - 'downharpoonleft;': '\u21c3', - 'downharpoonright;': '\u21c2', - 'DownLeftRightVector;': '\u2950', - 'DownLeftTeeVector;': '\u295e', - 'DownLeftVector;': '\u21bd', - 'DownLeftVectorBar;': '\u2956', - 'DownRightTeeVector;': '\u295f', - 'DownRightVector;': '\u21c1', - 'DownRightVectorBar;': '\u2957', - 'DownTee;': '\u22a4', - 'DownTeeArrow;': '\u21a7', - 'drbkarow;': '\u2910', - 'drcorn;': '\u231f', - 'drcrop;': '\u230c', - 'Dscr;': '\U0001d49f', - 'dscr;': '\U0001d4b9', - 'DScy;': '\u0405', - 'dscy;': '\u0455', - 'dsol;': '\u29f6', - 'Dstrok;': '\u0110', - 'dstrok;': '\u0111', - 'dtdot;': '\u22f1', - 'dtri;': '\u25bf', - 'dtrif;': '\u25be', - 'duarr;': '\u21f5', - 'duhar;': '\u296f', - 'dwangle;': '\u29a6', - 'DZcy;': '\u040f', - 'dzcy;': '\u045f', - 'dzigrarr;': '\u27ff', - 'Eacute': '\xc9', - 'eacute': '\xe9', - 'Eacute;': '\xc9', - 'eacute;': '\xe9', - 'easter;': '\u2a6e', - 'Ecaron;': '\u011a', - 'ecaron;': '\u011b', - 'ecir;': '\u2256', - 'Ecirc': '\xca', - 'ecirc': '\xea', - 'Ecirc;': '\xca', - 'ecirc;': '\xea', - 'ecolon;': '\u2255', - 'Ecy;': '\u042d', - 'ecy;': '\u044d', - 'eDDot;': '\u2a77', - 'Edot;': '\u0116', - 'eDot;': '\u2251', - 'edot;': '\u0117', - 'ee;': '\u2147', - 'efDot;': '\u2252', - 'Efr;': '\U0001d508', - 'efr;': '\U0001d522', - 'eg;': '\u2a9a', - 'Egrave': '\xc8', - 'egrave': '\xe8', - 'Egrave;': '\xc8', - 'egrave;': '\xe8', - 'egs;': '\u2a96', - 'egsdot;': '\u2a98', - 'el;': '\u2a99', - 'Element;': '\u2208', - 'elinters;': '\u23e7', - 'ell;': '\u2113', - 'els;': '\u2a95', - 'elsdot;': '\u2a97', - 'Emacr;': '\u0112', - 'emacr;': '\u0113', - 'empty;': '\u2205', - 'emptyset;': '\u2205', - 'EmptySmallSquare;': '\u25fb', - 'emptyv;': '\u2205', - 'EmptyVerySmallSquare;': '\u25ab', - 'emsp13;': '\u2004', - 'emsp14;': '\u2005', - 'emsp;': '\u2003', - 'ENG;': '\u014a', - 'eng;': '\u014b', - 'ensp;': '\u2002', - 'Eogon;': '\u0118', - 'eogon;': '\u0119', - 'Eopf;': '\U0001d53c', - 'eopf;': '\U0001d556', - 'epar;': '\u22d5', - 'eparsl;': '\u29e3', - 'eplus;': '\u2a71', - 'epsi;': '\u03b5', - 'Epsilon;': '\u0395', - 'epsilon;': '\u03b5', - 'epsiv;': '\u03f5', - 'eqcirc;': '\u2256', - 'eqcolon;': '\u2255', - 'eqsim;': '\u2242', - 'eqslantgtr;': '\u2a96', - 'eqslantless;': '\u2a95', - 'Equal;': '\u2a75', - 'equals;': '=', - 'EqualTilde;': '\u2242', - 'equest;': '\u225f', - 'Equilibrium;': '\u21cc', - 'equiv;': '\u2261', - 'equivDD;': '\u2a78', - 'eqvparsl;': '\u29e5', - 'erarr;': '\u2971', - 'erDot;': '\u2253', - 'Escr;': '\u2130', - 'escr;': '\u212f', - 'esdot;': '\u2250', - 'Esim;': '\u2a73', - 'esim;': '\u2242', - 'Eta;': '\u0397', - 'eta;': '\u03b7', - 'ETH': '\xd0', - 'eth': '\xf0', - 'ETH;': '\xd0', - 'eth;': '\xf0', - 'Euml': '\xcb', - 'euml': '\xeb', - 'Euml;': '\xcb', - 'euml;': '\xeb', - 'euro;': '\u20ac', - 'excl;': '!', - 'exist;': '\u2203', - 'Exists;': '\u2203', - 'expectation;': '\u2130', - 'ExponentialE;': '\u2147', - 'exponentiale;': '\u2147', - 'fallingdotseq;': '\u2252', - 'Fcy;': '\u0424', - 'fcy;': '\u0444', - 'female;': '\u2640', - 'ffilig;': '\ufb03', - 'fflig;': '\ufb00', - 'ffllig;': '\ufb04', - 'Ffr;': '\U0001d509', - 'ffr;': '\U0001d523', - 'filig;': '\ufb01', - 'FilledSmallSquare;': '\u25fc', - 'FilledVerySmallSquare;': '\u25aa', - 'fjlig;': 'fj', - 'flat;': '\u266d', - 'fllig;': '\ufb02', - 'fltns;': '\u25b1', - 'fnof;': '\u0192', - 'Fopf;': '\U0001d53d', - 'fopf;': '\U0001d557', - 'ForAll;': '\u2200', - 'forall;': '\u2200', - 'fork;': '\u22d4', - 'forkv;': '\u2ad9', - 'Fouriertrf;': '\u2131', - 'fpartint;': '\u2a0d', - 'frac12': '\xbd', - 'frac12;': '\xbd', - 'frac13;': '\u2153', - 'frac14': '\xbc', - 'frac14;': '\xbc', - 'frac15;': '\u2155', - 'frac16;': '\u2159', - 'frac18;': '\u215b', - 'frac23;': '\u2154', - 'frac25;': '\u2156', - 'frac34': '\xbe', - 'frac34;': '\xbe', - 'frac35;': '\u2157', - 'frac38;': '\u215c', - 'frac45;': '\u2158', - 'frac56;': '\u215a', - 'frac58;': '\u215d', - 'frac78;': '\u215e', - 'frasl;': '\u2044', - 'frown;': '\u2322', - 'Fscr;': '\u2131', - 'fscr;': '\U0001d4bb', - 'gacute;': '\u01f5', - 'Gamma;': '\u0393', - 'gamma;': '\u03b3', - 'Gammad;': '\u03dc', - 'gammad;': '\u03dd', - 'gap;': '\u2a86', - 'Gbreve;': '\u011e', - 'gbreve;': '\u011f', - 'Gcedil;': '\u0122', - 'Gcirc;': '\u011c', - 'gcirc;': '\u011d', - 'Gcy;': '\u0413', - 'gcy;': '\u0433', - 'Gdot;': '\u0120', - 'gdot;': '\u0121', - 'gE;': '\u2267', - 'ge;': '\u2265', - 'gEl;': '\u2a8c', - 'gel;': '\u22db', - 'geq;': '\u2265', - 'geqq;': '\u2267', - 'geqslant;': '\u2a7e', - 'ges;': '\u2a7e', - 'gescc;': '\u2aa9', - 'gesdot;': '\u2a80', - 'gesdoto;': '\u2a82', - 'gesdotol;': '\u2a84', - 'gesl;': '\u22db\ufe00', - 'gesles;': '\u2a94', - 'Gfr;': '\U0001d50a', - 'gfr;': '\U0001d524', - 'Gg;': '\u22d9', - 'gg;': '\u226b', - 'ggg;': '\u22d9', - 'gimel;': '\u2137', - 'GJcy;': '\u0403', - 'gjcy;': '\u0453', - 'gl;': '\u2277', - 'gla;': '\u2aa5', - 'glE;': '\u2a92', - 'glj;': '\u2aa4', - 'gnap;': '\u2a8a', - 'gnapprox;': '\u2a8a', - 'gnE;': '\u2269', - 'gne;': '\u2a88', - 'gneq;': '\u2a88', - 'gneqq;': '\u2269', - 'gnsim;': '\u22e7', - 'Gopf;': '\U0001d53e', - 'gopf;': '\U0001d558', - 'grave;': '`', - 'GreaterEqual;': '\u2265', - 'GreaterEqualLess;': '\u22db', - 'GreaterFullEqual;': '\u2267', - 'GreaterGreater;': '\u2aa2', - 'GreaterLess;': '\u2277', - 'GreaterSlantEqual;': '\u2a7e', - 'GreaterTilde;': '\u2273', - 'Gscr;': '\U0001d4a2', - 'gscr;': '\u210a', - 'gsim;': '\u2273', - 'gsime;': '\u2a8e', - 'gsiml;': '\u2a90', - 'GT': '>', - 'gt': '>', - 'GT;': '>', - 'Gt;': '\u226b', - 'gt;': '>', - 'gtcc;': '\u2aa7', - 'gtcir;': '\u2a7a', - 'gtdot;': '\u22d7', - 'gtlPar;': '\u2995', - 'gtquest;': '\u2a7c', - 'gtrapprox;': '\u2a86', - 'gtrarr;': '\u2978', - 'gtrdot;': '\u22d7', - 'gtreqless;': '\u22db', - 'gtreqqless;': '\u2a8c', - 'gtrless;': '\u2277', - 'gtrsim;': '\u2273', - 'gvertneqq;': '\u2269\ufe00', - 'gvnE;': '\u2269\ufe00', - 'Hacek;': '\u02c7', - 'hairsp;': '\u200a', - 'half;': '\xbd', - 'hamilt;': '\u210b', - 'HARDcy;': '\u042a', - 'hardcy;': '\u044a', - 'hArr;': '\u21d4', - 'harr;': '\u2194', - 'harrcir;': '\u2948', - 'harrw;': '\u21ad', - 'Hat;': '^', - 'hbar;': '\u210f', - 'Hcirc;': '\u0124', - 'hcirc;': '\u0125', - 'hearts;': '\u2665', - 'heartsuit;': '\u2665', - 'hellip;': '\u2026', - 'hercon;': '\u22b9', - 'Hfr;': '\u210c', - 'hfr;': '\U0001d525', - 'HilbertSpace;': '\u210b', - 'hksearow;': '\u2925', - 'hkswarow;': '\u2926', - 'hoarr;': '\u21ff', - 'homtht;': '\u223b', - 'hookleftarrow;': '\u21a9', - 'hookrightarrow;': '\u21aa', - 'Hopf;': '\u210d', - 'hopf;': '\U0001d559', - 'horbar;': '\u2015', - 'HorizontalLine;': '\u2500', - 'Hscr;': '\u210b', - 'hscr;': '\U0001d4bd', - 'hslash;': '\u210f', - 'Hstrok;': '\u0126', - 'hstrok;': '\u0127', - 'HumpDownHump;': '\u224e', - 'HumpEqual;': '\u224f', - 'hybull;': '\u2043', - 'hyphen;': '\u2010', - 'Iacute': '\xcd', - 'iacute': '\xed', - 'Iacute;': '\xcd', - 'iacute;': '\xed', - 'ic;': '\u2063', - 'Icirc': '\xce', - 'icirc': '\xee', - 'Icirc;': '\xce', - 'icirc;': '\xee', - 'Icy;': '\u0418', - 'icy;': '\u0438', - 'Idot;': '\u0130', - 'IEcy;': '\u0415', - 'iecy;': '\u0435', - 'iexcl': '\xa1', - 'iexcl;': '\xa1', - 'iff;': '\u21d4', - 'Ifr;': '\u2111', - 'ifr;': '\U0001d526', - 'Igrave': '\xcc', - 'igrave': '\xec', - 'Igrave;': '\xcc', - 'igrave;': '\xec', - 'ii;': '\u2148', - 'iiiint;': '\u2a0c', - 'iiint;': '\u222d', - 'iinfin;': '\u29dc', - 'iiota;': '\u2129', - 'IJlig;': '\u0132', - 'ijlig;': '\u0133', - 'Im;': '\u2111', - 'Imacr;': '\u012a', - 'imacr;': '\u012b', - 'image;': '\u2111', - 'ImaginaryI;': '\u2148', - 'imagline;': '\u2110', - 'imagpart;': '\u2111', - 'imath;': '\u0131', - 'imof;': '\u22b7', - 'imped;': '\u01b5', - 'Implies;': '\u21d2', - 'in;': '\u2208', - 'incare;': '\u2105', - 'infin;': '\u221e', - 'infintie;': '\u29dd', - 'inodot;': '\u0131', - 'Int;': '\u222c', - 'int;': '\u222b', - 'intcal;': '\u22ba', - 'integers;': '\u2124', - 'Integral;': '\u222b', - 'intercal;': '\u22ba', - 'Intersection;': '\u22c2', - 'intlarhk;': '\u2a17', - 'intprod;': '\u2a3c', - 'InvisibleComma;': '\u2063', - 'InvisibleTimes;': '\u2062', - 'IOcy;': '\u0401', - 'iocy;': '\u0451', - 'Iogon;': '\u012e', - 'iogon;': '\u012f', - 'Iopf;': '\U0001d540', - 'iopf;': '\U0001d55a', - 'Iota;': '\u0399', - 'iota;': '\u03b9', - 'iprod;': '\u2a3c', - 'iquest': '\xbf', - 'iquest;': '\xbf', - 'Iscr;': '\u2110', - 'iscr;': '\U0001d4be', - 'isin;': '\u2208', - 'isindot;': '\u22f5', - 'isinE;': '\u22f9', - 'isins;': '\u22f4', - 'isinsv;': '\u22f3', - 'isinv;': '\u2208', - 'it;': '\u2062', - 'Itilde;': '\u0128', - 'itilde;': '\u0129', - 'Iukcy;': '\u0406', - 'iukcy;': '\u0456', - 'Iuml': '\xcf', - 'iuml': '\xef', - 'Iuml;': '\xcf', - 'iuml;': '\xef', - 'Jcirc;': '\u0134', - 'jcirc;': '\u0135', - 'Jcy;': '\u0419', - 'jcy;': '\u0439', - 'Jfr;': '\U0001d50d', - 'jfr;': '\U0001d527', - 'jmath;': '\u0237', - 'Jopf;': '\U0001d541', - 'jopf;': '\U0001d55b', - 'Jscr;': '\U0001d4a5', - 'jscr;': '\U0001d4bf', - 'Jsercy;': '\u0408', - 'jsercy;': '\u0458', - 'Jukcy;': '\u0404', - 'jukcy;': '\u0454', - 'Kappa;': '\u039a', - 'kappa;': '\u03ba', - 'kappav;': '\u03f0', - 'Kcedil;': '\u0136', - 'kcedil;': '\u0137', - 'Kcy;': '\u041a', - 'kcy;': '\u043a', - 'Kfr;': '\U0001d50e', - 'kfr;': '\U0001d528', - 'kgreen;': '\u0138', - 'KHcy;': '\u0425', - 'khcy;': '\u0445', - 'KJcy;': '\u040c', - 'kjcy;': '\u045c', - 'Kopf;': '\U0001d542', - 'kopf;': '\U0001d55c', - 'Kscr;': '\U0001d4a6', - 'kscr;': '\U0001d4c0', - 'lAarr;': '\u21da', - 'Lacute;': '\u0139', - 'lacute;': '\u013a', - 'laemptyv;': '\u29b4', - 'lagran;': '\u2112', - 'Lambda;': '\u039b', - 'lambda;': '\u03bb', - 'Lang;': '\u27ea', - 'lang;': '\u27e8', - 'langd;': '\u2991', - 'langle;': '\u27e8', - 'lap;': '\u2a85', - 'Laplacetrf;': '\u2112', - 'laquo': '\xab', - 'laquo;': '\xab', - 'Larr;': '\u219e', - 'lArr;': '\u21d0', - 'larr;': '\u2190', - 'larrb;': '\u21e4', - 'larrbfs;': '\u291f', - 'larrfs;': '\u291d', - 'larrhk;': '\u21a9', - 'larrlp;': '\u21ab', - 'larrpl;': '\u2939', - 'larrsim;': '\u2973', - 'larrtl;': '\u21a2', - 'lat;': '\u2aab', - 'lAtail;': '\u291b', - 'latail;': '\u2919', - 'late;': '\u2aad', - 'lates;': '\u2aad\ufe00', - 'lBarr;': '\u290e', - 'lbarr;': '\u290c', - 'lbbrk;': '\u2772', - 'lbrace;': '{', - 'lbrack;': '[', - 'lbrke;': '\u298b', - 'lbrksld;': '\u298f', - 'lbrkslu;': '\u298d', - 'Lcaron;': '\u013d', - 'lcaron;': '\u013e', - 'Lcedil;': '\u013b', - 'lcedil;': '\u013c', - 'lceil;': '\u2308', - 'lcub;': '{', - 'Lcy;': '\u041b', - 'lcy;': '\u043b', - 'ldca;': '\u2936', - 'ldquo;': '\u201c', - 'ldquor;': '\u201e', - 'ldrdhar;': '\u2967', - 'ldrushar;': '\u294b', - 'ldsh;': '\u21b2', - 'lE;': '\u2266', - 'le;': '\u2264', - 'LeftAngleBracket;': '\u27e8', - 'LeftArrow;': '\u2190', - 'Leftarrow;': '\u21d0', - 'leftarrow;': '\u2190', - 'LeftArrowBar;': '\u21e4', - 'LeftArrowRightArrow;': '\u21c6', - 'leftarrowtail;': '\u21a2', - 'LeftCeiling;': '\u2308', - 'LeftDoubleBracket;': '\u27e6', - 'LeftDownTeeVector;': '\u2961', - 'LeftDownVector;': '\u21c3', - 'LeftDownVectorBar;': '\u2959', - 'LeftFloor;': '\u230a', - 'leftharpoondown;': '\u21bd', - 'leftharpoonup;': '\u21bc', - 'leftleftarrows;': '\u21c7', - 'LeftRightArrow;': '\u2194', - 'Leftrightarrow;': '\u21d4', - 'leftrightarrow;': '\u2194', - 'leftrightarrows;': '\u21c6', - 'leftrightharpoons;': '\u21cb', - 'leftrightsquigarrow;': '\u21ad', - 'LeftRightVector;': '\u294e', - 'LeftTee;': '\u22a3', - 'LeftTeeArrow;': '\u21a4', - 'LeftTeeVector;': '\u295a', - 'leftthreetimes;': '\u22cb', - 'LeftTriangle;': '\u22b2', - 'LeftTriangleBar;': '\u29cf', - 'LeftTriangleEqual;': '\u22b4', - 'LeftUpDownVector;': '\u2951', - 'LeftUpTeeVector;': '\u2960', - 'LeftUpVector;': '\u21bf', - 'LeftUpVectorBar;': '\u2958', - 'LeftVector;': '\u21bc', - 'LeftVectorBar;': '\u2952', - 'lEg;': '\u2a8b', - 'leg;': '\u22da', - 'leq;': '\u2264', - 'leqq;': '\u2266', - 'leqslant;': '\u2a7d', - 'les;': '\u2a7d', - 'lescc;': '\u2aa8', - 'lesdot;': '\u2a7f', - 'lesdoto;': '\u2a81', - 'lesdotor;': '\u2a83', - 'lesg;': '\u22da\ufe00', - 'lesges;': '\u2a93', - 'lessapprox;': '\u2a85', - 'lessdot;': '\u22d6', - 'lesseqgtr;': '\u22da', - 'lesseqqgtr;': '\u2a8b', - 'LessEqualGreater;': '\u22da', - 'LessFullEqual;': '\u2266', - 'LessGreater;': '\u2276', - 'lessgtr;': '\u2276', - 'LessLess;': '\u2aa1', - 'lesssim;': '\u2272', - 'LessSlantEqual;': '\u2a7d', - 'LessTilde;': '\u2272', - 'lfisht;': '\u297c', - 'lfloor;': '\u230a', - 'Lfr;': '\U0001d50f', - 'lfr;': '\U0001d529', - 'lg;': '\u2276', - 'lgE;': '\u2a91', - 'lHar;': '\u2962', - 'lhard;': '\u21bd', - 'lharu;': '\u21bc', - 'lharul;': '\u296a', - 'lhblk;': '\u2584', - 'LJcy;': '\u0409', - 'ljcy;': '\u0459', - 'Ll;': '\u22d8', - 'll;': '\u226a', - 'llarr;': '\u21c7', - 'llcorner;': '\u231e', - 'Lleftarrow;': '\u21da', - 'llhard;': '\u296b', - 'lltri;': '\u25fa', - 'Lmidot;': '\u013f', - 'lmidot;': '\u0140', - 'lmoust;': '\u23b0', - 'lmoustache;': '\u23b0', - 'lnap;': '\u2a89', - 'lnapprox;': '\u2a89', - 'lnE;': '\u2268', - 'lne;': '\u2a87', - 'lneq;': '\u2a87', - 'lneqq;': '\u2268', - 'lnsim;': '\u22e6', - 'loang;': '\u27ec', - 'loarr;': '\u21fd', - 'lobrk;': '\u27e6', - 'LongLeftArrow;': '\u27f5', - 'Longleftarrow;': '\u27f8', - 'longleftarrow;': '\u27f5', - 'LongLeftRightArrow;': '\u27f7', - 'Longleftrightarrow;': '\u27fa', - 'longleftrightarrow;': '\u27f7', - 'longmapsto;': '\u27fc', - 'LongRightArrow;': '\u27f6', - 'Longrightarrow;': '\u27f9', - 'longrightarrow;': '\u27f6', - 'looparrowleft;': '\u21ab', - 'looparrowright;': '\u21ac', - 'lopar;': '\u2985', - 'Lopf;': '\U0001d543', - 'lopf;': '\U0001d55d', - 'loplus;': '\u2a2d', - 'lotimes;': '\u2a34', - 'lowast;': '\u2217', - 'lowbar;': '_', - 'LowerLeftArrow;': '\u2199', - 'LowerRightArrow;': '\u2198', - 'loz;': '\u25ca', - 'lozenge;': '\u25ca', - 'lozf;': '\u29eb', - 'lpar;': '(', - 'lparlt;': '\u2993', - 'lrarr;': '\u21c6', - 'lrcorner;': '\u231f', - 'lrhar;': '\u21cb', - 'lrhard;': '\u296d', - 'lrm;': '\u200e', - 'lrtri;': '\u22bf', - 'lsaquo;': '\u2039', - 'Lscr;': '\u2112', - 'lscr;': '\U0001d4c1', - 'Lsh;': '\u21b0', - 'lsh;': '\u21b0', - 'lsim;': '\u2272', - 'lsime;': '\u2a8d', - 'lsimg;': '\u2a8f', - 'lsqb;': '[', - 'lsquo;': '\u2018', - 'lsquor;': '\u201a', - 'Lstrok;': '\u0141', - 'lstrok;': '\u0142', - 'LT': '<', - 'lt': '<', - 'LT;': '<', - 'Lt;': '\u226a', - 'lt;': '<', - 'ltcc;': '\u2aa6', - 'ltcir;': '\u2a79', - 'ltdot;': '\u22d6', - 'lthree;': '\u22cb', - 'ltimes;': '\u22c9', - 'ltlarr;': '\u2976', - 'ltquest;': '\u2a7b', - 'ltri;': '\u25c3', - 'ltrie;': '\u22b4', - 'ltrif;': '\u25c2', - 'ltrPar;': '\u2996', - 'lurdshar;': '\u294a', - 'luruhar;': '\u2966', - 'lvertneqq;': '\u2268\ufe00', - 'lvnE;': '\u2268\ufe00', - 'macr': '\xaf', - 'macr;': '\xaf', - 'male;': '\u2642', - 'malt;': '\u2720', - 'maltese;': '\u2720', - 'Map;': '\u2905', - 'map;': '\u21a6', - 'mapsto;': '\u21a6', - 'mapstodown;': '\u21a7', - 'mapstoleft;': '\u21a4', - 'mapstoup;': '\u21a5', - 'marker;': '\u25ae', - 'mcomma;': '\u2a29', - 'Mcy;': '\u041c', - 'mcy;': '\u043c', - 'mdash;': '\u2014', - 'mDDot;': '\u223a', - 'measuredangle;': '\u2221', - 'MediumSpace;': '\u205f', - 'Mellintrf;': '\u2133', - 'Mfr;': '\U0001d510', - 'mfr;': '\U0001d52a', - 'mho;': '\u2127', - 'micro': '\xb5', - 'micro;': '\xb5', - 'mid;': '\u2223', - 'midast;': '*', - 'midcir;': '\u2af0', - 'middot': '\xb7', - 'middot;': '\xb7', - 'minus;': '\u2212', - 'minusb;': '\u229f', - 'minusd;': '\u2238', - 'minusdu;': '\u2a2a', - 'MinusPlus;': '\u2213', - 'mlcp;': '\u2adb', - 'mldr;': '\u2026', - 'mnplus;': '\u2213', - 'models;': '\u22a7', - 'Mopf;': '\U0001d544', - 'mopf;': '\U0001d55e', - 'mp;': '\u2213', - 'Mscr;': '\u2133', - 'mscr;': '\U0001d4c2', - 'mstpos;': '\u223e', - 'Mu;': '\u039c', - 'mu;': '\u03bc', - 'multimap;': '\u22b8', - 'mumap;': '\u22b8', - 'nabla;': '\u2207', - 'Nacute;': '\u0143', - 'nacute;': '\u0144', - 'nang;': '\u2220\u20d2', - 'nap;': '\u2249', - 'napE;': '\u2a70\u0338', - 'napid;': '\u224b\u0338', - 'napos;': '\u0149', - 'napprox;': '\u2249', - 'natur;': '\u266e', - 'natural;': '\u266e', - 'naturals;': '\u2115', - 'nbsp': '\xa0', - 'nbsp;': '\xa0', - 'nbump;': '\u224e\u0338', - 'nbumpe;': '\u224f\u0338', - 'ncap;': '\u2a43', - 'Ncaron;': '\u0147', - 'ncaron;': '\u0148', - 'Ncedil;': '\u0145', - 'ncedil;': '\u0146', - 'ncong;': '\u2247', - 'ncongdot;': '\u2a6d\u0338', - 'ncup;': '\u2a42', - 'Ncy;': '\u041d', - 'ncy;': '\u043d', - 'ndash;': '\u2013', - 'ne;': '\u2260', - 'nearhk;': '\u2924', - 'neArr;': '\u21d7', - 'nearr;': '\u2197', - 'nearrow;': '\u2197', - 'nedot;': '\u2250\u0338', - 'NegativeMediumSpace;': '\u200b', - 'NegativeThickSpace;': '\u200b', - 'NegativeThinSpace;': '\u200b', - 'NegativeVeryThinSpace;': '\u200b', - 'nequiv;': '\u2262', - 'nesear;': '\u2928', - 'nesim;': '\u2242\u0338', - 'NestedGreaterGreater;': '\u226b', - 'NestedLessLess;': '\u226a', - 'NewLine;': '\n', - 'nexist;': '\u2204', - 'nexists;': '\u2204', - 'Nfr;': '\U0001d511', - 'nfr;': '\U0001d52b', - 'ngE;': '\u2267\u0338', - 'nge;': '\u2271', - 'ngeq;': '\u2271', - 'ngeqq;': '\u2267\u0338', - 'ngeqslant;': '\u2a7e\u0338', - 'nges;': '\u2a7e\u0338', - 'nGg;': '\u22d9\u0338', - 'ngsim;': '\u2275', - 'nGt;': '\u226b\u20d2', - 'ngt;': '\u226f', - 'ngtr;': '\u226f', - 'nGtv;': '\u226b\u0338', - 'nhArr;': '\u21ce', - 'nharr;': '\u21ae', - 'nhpar;': '\u2af2', - 'ni;': '\u220b', - 'nis;': '\u22fc', - 'nisd;': '\u22fa', - 'niv;': '\u220b', - 'NJcy;': '\u040a', - 'njcy;': '\u045a', - 'nlArr;': '\u21cd', - 'nlarr;': '\u219a', - 'nldr;': '\u2025', - 'nlE;': '\u2266\u0338', - 'nle;': '\u2270', - 'nLeftarrow;': '\u21cd', - 'nleftarrow;': '\u219a', - 'nLeftrightarrow;': '\u21ce', - 'nleftrightarrow;': '\u21ae', - 'nleq;': '\u2270', - 'nleqq;': '\u2266\u0338', - 'nleqslant;': '\u2a7d\u0338', - 'nles;': '\u2a7d\u0338', - 'nless;': '\u226e', - 'nLl;': '\u22d8\u0338', - 'nlsim;': '\u2274', - 'nLt;': '\u226a\u20d2', - 'nlt;': '\u226e', - 'nltri;': '\u22ea', - 'nltrie;': '\u22ec', - 'nLtv;': '\u226a\u0338', - 'nmid;': '\u2224', - 'NoBreak;': '\u2060', - 'NonBreakingSpace;': '\xa0', - 'Nopf;': '\u2115', - 'nopf;': '\U0001d55f', - 'not': '\xac', - 'Not;': '\u2aec', - 'not;': '\xac', - 'NotCongruent;': '\u2262', - 'NotCupCap;': '\u226d', - 'NotDoubleVerticalBar;': '\u2226', - 'NotElement;': '\u2209', - 'NotEqual;': '\u2260', - 'NotEqualTilde;': '\u2242\u0338', - 'NotExists;': '\u2204', - 'NotGreater;': '\u226f', - 'NotGreaterEqual;': '\u2271', - 'NotGreaterFullEqual;': '\u2267\u0338', - 'NotGreaterGreater;': '\u226b\u0338', - 'NotGreaterLess;': '\u2279', - 'NotGreaterSlantEqual;': '\u2a7e\u0338', - 'NotGreaterTilde;': '\u2275', - 'NotHumpDownHump;': '\u224e\u0338', - 'NotHumpEqual;': '\u224f\u0338', - 'notin;': '\u2209', - 'notindot;': '\u22f5\u0338', - 'notinE;': '\u22f9\u0338', - 'notinva;': '\u2209', - 'notinvb;': '\u22f7', - 'notinvc;': '\u22f6', - 'NotLeftTriangle;': '\u22ea', - 'NotLeftTriangleBar;': '\u29cf\u0338', - 'NotLeftTriangleEqual;': '\u22ec', - 'NotLess;': '\u226e', - 'NotLessEqual;': '\u2270', - 'NotLessGreater;': '\u2278', - 'NotLessLess;': '\u226a\u0338', - 'NotLessSlantEqual;': '\u2a7d\u0338', - 'NotLessTilde;': '\u2274', - 'NotNestedGreaterGreater;': '\u2aa2\u0338', - 'NotNestedLessLess;': '\u2aa1\u0338', - 'notni;': '\u220c', - 'notniva;': '\u220c', - 'notnivb;': '\u22fe', - 'notnivc;': '\u22fd', - 'NotPrecedes;': '\u2280', - 'NotPrecedesEqual;': '\u2aaf\u0338', - 'NotPrecedesSlantEqual;': '\u22e0', - 'NotReverseElement;': '\u220c', - 'NotRightTriangle;': '\u22eb', - 'NotRightTriangleBar;': '\u29d0\u0338', - 'NotRightTriangleEqual;': '\u22ed', - 'NotSquareSubset;': '\u228f\u0338', - 'NotSquareSubsetEqual;': '\u22e2', - 'NotSquareSuperset;': '\u2290\u0338', - 'NotSquareSupersetEqual;': '\u22e3', - 'NotSubset;': '\u2282\u20d2', - 'NotSubsetEqual;': '\u2288', - 'NotSucceeds;': '\u2281', - 'NotSucceedsEqual;': '\u2ab0\u0338', - 'NotSucceedsSlantEqual;': '\u22e1', - 'NotSucceedsTilde;': '\u227f\u0338', - 'NotSuperset;': '\u2283\u20d2', - 'NotSupersetEqual;': '\u2289', - 'NotTilde;': '\u2241', - 'NotTildeEqual;': '\u2244', - 'NotTildeFullEqual;': '\u2247', - 'NotTildeTilde;': '\u2249', - 'NotVerticalBar;': '\u2224', - 'npar;': '\u2226', - 'nparallel;': '\u2226', - 'nparsl;': '\u2afd\u20e5', - 'npart;': '\u2202\u0338', - 'npolint;': '\u2a14', - 'npr;': '\u2280', - 'nprcue;': '\u22e0', - 'npre;': '\u2aaf\u0338', - 'nprec;': '\u2280', - 'npreceq;': '\u2aaf\u0338', - 'nrArr;': '\u21cf', - 'nrarr;': '\u219b', - 'nrarrc;': '\u2933\u0338', - 'nrarrw;': '\u219d\u0338', - 'nRightarrow;': '\u21cf', - 'nrightarrow;': '\u219b', - 'nrtri;': '\u22eb', - 'nrtrie;': '\u22ed', - 'nsc;': '\u2281', - 'nsccue;': '\u22e1', - 'nsce;': '\u2ab0\u0338', - 'Nscr;': '\U0001d4a9', - 'nscr;': '\U0001d4c3', - 'nshortmid;': '\u2224', - 'nshortparallel;': '\u2226', - 'nsim;': '\u2241', - 'nsime;': '\u2244', - 'nsimeq;': '\u2244', - 'nsmid;': '\u2224', - 'nspar;': '\u2226', - 'nsqsube;': '\u22e2', - 'nsqsupe;': '\u22e3', - 'nsub;': '\u2284', - 'nsubE;': '\u2ac5\u0338', - 'nsube;': '\u2288', - 'nsubset;': '\u2282\u20d2', - 'nsubseteq;': '\u2288', - 'nsubseteqq;': '\u2ac5\u0338', - 'nsucc;': '\u2281', - 'nsucceq;': '\u2ab0\u0338', - 'nsup;': '\u2285', - 'nsupE;': '\u2ac6\u0338', - 'nsupe;': '\u2289', - 'nsupset;': '\u2283\u20d2', - 'nsupseteq;': '\u2289', - 'nsupseteqq;': '\u2ac6\u0338', - 'ntgl;': '\u2279', - 'Ntilde': '\xd1', - 'ntilde': '\xf1', - 'Ntilde;': '\xd1', - 'ntilde;': '\xf1', - 'ntlg;': '\u2278', - 'ntriangleleft;': '\u22ea', - 'ntrianglelefteq;': '\u22ec', - 'ntriangleright;': '\u22eb', - 'ntrianglerighteq;': '\u22ed', - 'Nu;': '\u039d', - 'nu;': '\u03bd', - 'num;': '#', - 'numero;': '\u2116', - 'numsp;': '\u2007', - 'nvap;': '\u224d\u20d2', - 'nVDash;': '\u22af', - 'nVdash;': '\u22ae', - 'nvDash;': '\u22ad', - 'nvdash;': '\u22ac', - 'nvge;': '\u2265\u20d2', - 'nvgt;': '>\u20d2', - 'nvHarr;': '\u2904', - 'nvinfin;': '\u29de', - 'nvlArr;': '\u2902', - 'nvle;': '\u2264\u20d2', - 'nvlt;': '<\u20d2', - 'nvltrie;': '\u22b4\u20d2', - 'nvrArr;': '\u2903', - 'nvrtrie;': '\u22b5\u20d2', - 'nvsim;': '\u223c\u20d2', - 'nwarhk;': '\u2923', - 'nwArr;': '\u21d6', - 'nwarr;': '\u2196', - 'nwarrow;': '\u2196', - 'nwnear;': '\u2927', - 'Oacute': '\xd3', - 'oacute': '\xf3', - 'Oacute;': '\xd3', - 'oacute;': '\xf3', - 'oast;': '\u229b', - 'ocir;': '\u229a', - 'Ocirc': '\xd4', - 'ocirc': '\xf4', - 'Ocirc;': '\xd4', - 'ocirc;': '\xf4', - 'Ocy;': '\u041e', - 'ocy;': '\u043e', - 'odash;': '\u229d', - 'Odblac;': '\u0150', - 'odblac;': '\u0151', - 'odiv;': '\u2a38', - 'odot;': '\u2299', - 'odsold;': '\u29bc', - 'OElig;': '\u0152', - 'oelig;': '\u0153', - 'ofcir;': '\u29bf', - 'Ofr;': '\U0001d512', - 'ofr;': '\U0001d52c', - 'ogon;': '\u02db', - 'Ograve': '\xd2', - 'ograve': '\xf2', - 'Ograve;': '\xd2', - 'ograve;': '\xf2', - 'ogt;': '\u29c1', - 'ohbar;': '\u29b5', - 'ohm;': '\u03a9', - 'oint;': '\u222e', - 'olarr;': '\u21ba', - 'olcir;': '\u29be', - 'olcross;': '\u29bb', - 'oline;': '\u203e', - 'olt;': '\u29c0', - 'Omacr;': '\u014c', - 'omacr;': '\u014d', - 'Omega;': '\u03a9', - 'omega;': '\u03c9', - 'Omicron;': '\u039f', - 'omicron;': '\u03bf', - 'omid;': '\u29b6', - 'ominus;': '\u2296', - 'Oopf;': '\U0001d546', - 'oopf;': '\U0001d560', - 'opar;': '\u29b7', - 'OpenCurlyDoubleQuote;': '\u201c', - 'OpenCurlyQuote;': '\u2018', - 'operp;': '\u29b9', - 'oplus;': '\u2295', - 'Or;': '\u2a54', - 'or;': '\u2228', - 'orarr;': '\u21bb', - 'ord;': '\u2a5d', - 'order;': '\u2134', - 'orderof;': '\u2134', - 'ordf': '\xaa', - 'ordf;': '\xaa', - 'ordm': '\xba', - 'ordm;': '\xba', - 'origof;': '\u22b6', - 'oror;': '\u2a56', - 'orslope;': '\u2a57', - 'orv;': '\u2a5b', - 'oS;': '\u24c8', - 'Oscr;': '\U0001d4aa', - 'oscr;': '\u2134', - 'Oslash': '\xd8', - 'oslash': '\xf8', - 'Oslash;': '\xd8', - 'oslash;': '\xf8', - 'osol;': '\u2298', - 'Otilde': '\xd5', - 'otilde': '\xf5', - 'Otilde;': '\xd5', - 'otilde;': '\xf5', - 'Otimes;': '\u2a37', - 'otimes;': '\u2297', - 'otimesas;': '\u2a36', - 'Ouml': '\xd6', - 'ouml': '\xf6', - 'Ouml;': '\xd6', - 'ouml;': '\xf6', - 'ovbar;': '\u233d', - 'OverBar;': '\u203e', - 'OverBrace;': '\u23de', - 'OverBracket;': '\u23b4', - 'OverParenthesis;': '\u23dc', - 'par;': '\u2225', - 'para': '\xb6', - 'para;': '\xb6', - 'parallel;': '\u2225', - 'parsim;': '\u2af3', - 'parsl;': '\u2afd', - 'part;': '\u2202', - 'PartialD;': '\u2202', - 'Pcy;': '\u041f', - 'pcy;': '\u043f', - 'percnt;': '%', - 'period;': '.', - 'permil;': '\u2030', - 'perp;': '\u22a5', - 'pertenk;': '\u2031', - 'Pfr;': '\U0001d513', - 'pfr;': '\U0001d52d', - 'Phi;': '\u03a6', - 'phi;': '\u03c6', - 'phiv;': '\u03d5', - 'phmmat;': '\u2133', - 'phone;': '\u260e', - 'Pi;': '\u03a0', - 'pi;': '\u03c0', - 'pitchfork;': '\u22d4', - 'piv;': '\u03d6', - 'planck;': '\u210f', - 'planckh;': '\u210e', - 'plankv;': '\u210f', - 'plus;': '+', - 'plusacir;': '\u2a23', - 'plusb;': '\u229e', - 'pluscir;': '\u2a22', - 'plusdo;': '\u2214', - 'plusdu;': '\u2a25', - 'pluse;': '\u2a72', - 'PlusMinus;': '\xb1', - 'plusmn': '\xb1', - 'plusmn;': '\xb1', - 'plussim;': '\u2a26', - 'plustwo;': '\u2a27', - 'pm;': '\xb1', - 'Poincareplane;': '\u210c', - 'pointint;': '\u2a15', - 'Popf;': '\u2119', - 'popf;': '\U0001d561', - 'pound': '\xa3', - 'pound;': '\xa3', - 'Pr;': '\u2abb', - 'pr;': '\u227a', - 'prap;': '\u2ab7', - 'prcue;': '\u227c', - 'prE;': '\u2ab3', - 'pre;': '\u2aaf', - 'prec;': '\u227a', - 'precapprox;': '\u2ab7', - 'preccurlyeq;': '\u227c', - 'Precedes;': '\u227a', - 'PrecedesEqual;': '\u2aaf', - 'PrecedesSlantEqual;': '\u227c', - 'PrecedesTilde;': '\u227e', - 'preceq;': '\u2aaf', - 'precnapprox;': '\u2ab9', - 'precneqq;': '\u2ab5', - 'precnsim;': '\u22e8', - 'precsim;': '\u227e', - 'Prime;': '\u2033', - 'prime;': '\u2032', - 'primes;': '\u2119', - 'prnap;': '\u2ab9', - 'prnE;': '\u2ab5', - 'prnsim;': '\u22e8', - 'prod;': '\u220f', - 'Product;': '\u220f', - 'profalar;': '\u232e', - 'profline;': '\u2312', - 'profsurf;': '\u2313', - 'prop;': '\u221d', - 'Proportion;': '\u2237', - 'Proportional;': '\u221d', - 'propto;': '\u221d', - 'prsim;': '\u227e', - 'prurel;': '\u22b0', - 'Pscr;': '\U0001d4ab', - 'pscr;': '\U0001d4c5', - 'Psi;': '\u03a8', - 'psi;': '\u03c8', - 'puncsp;': '\u2008', - 'Qfr;': '\U0001d514', - 'qfr;': '\U0001d52e', - 'qint;': '\u2a0c', - 'Qopf;': '\u211a', - 'qopf;': '\U0001d562', - 'qprime;': '\u2057', - 'Qscr;': '\U0001d4ac', - 'qscr;': '\U0001d4c6', - 'quaternions;': '\u210d', - 'quatint;': '\u2a16', - 'quest;': '?', - 'questeq;': '\u225f', - 'QUOT': '"', - 'quot': '"', - 'QUOT;': '"', - 'quot;': '"', - 'rAarr;': '\u21db', - 'race;': '\u223d\u0331', - 'Racute;': '\u0154', - 'racute;': '\u0155', - 'radic;': '\u221a', - 'raemptyv;': '\u29b3', - 'Rang;': '\u27eb', - 'rang;': '\u27e9', - 'rangd;': '\u2992', - 'range;': '\u29a5', - 'rangle;': '\u27e9', - 'raquo': '\xbb', - 'raquo;': '\xbb', - 'Rarr;': '\u21a0', - 'rArr;': '\u21d2', - 'rarr;': '\u2192', - 'rarrap;': '\u2975', - 'rarrb;': '\u21e5', - 'rarrbfs;': '\u2920', - 'rarrc;': '\u2933', - 'rarrfs;': '\u291e', - 'rarrhk;': '\u21aa', - 'rarrlp;': '\u21ac', - 'rarrpl;': '\u2945', - 'rarrsim;': '\u2974', - 'Rarrtl;': '\u2916', - 'rarrtl;': '\u21a3', - 'rarrw;': '\u219d', - 'rAtail;': '\u291c', - 'ratail;': '\u291a', - 'ratio;': '\u2236', - 'rationals;': '\u211a', - 'RBarr;': '\u2910', - 'rBarr;': '\u290f', - 'rbarr;': '\u290d', - 'rbbrk;': '\u2773', - 'rbrace;': '}', - 'rbrack;': ']', - 'rbrke;': '\u298c', - 'rbrksld;': '\u298e', - 'rbrkslu;': '\u2990', - 'Rcaron;': '\u0158', - 'rcaron;': '\u0159', - 'Rcedil;': '\u0156', - 'rcedil;': '\u0157', - 'rceil;': '\u2309', - 'rcub;': '}', - 'Rcy;': '\u0420', - 'rcy;': '\u0440', - 'rdca;': '\u2937', - 'rdldhar;': '\u2969', - 'rdquo;': '\u201d', - 'rdquor;': '\u201d', - 'rdsh;': '\u21b3', - 'Re;': '\u211c', - 'real;': '\u211c', - 'realine;': '\u211b', - 'realpart;': '\u211c', - 'reals;': '\u211d', - 'rect;': '\u25ad', - 'REG': '\xae', - 'reg': '\xae', - 'REG;': '\xae', - 'reg;': '\xae', - 'ReverseElement;': '\u220b', - 'ReverseEquilibrium;': '\u21cb', - 'ReverseUpEquilibrium;': '\u296f', - 'rfisht;': '\u297d', - 'rfloor;': '\u230b', - 'Rfr;': '\u211c', - 'rfr;': '\U0001d52f', - 'rHar;': '\u2964', - 'rhard;': '\u21c1', - 'rharu;': '\u21c0', - 'rharul;': '\u296c', - 'Rho;': '\u03a1', - 'rho;': '\u03c1', - 'rhov;': '\u03f1', - 'RightAngleBracket;': '\u27e9', - 'RightArrow;': '\u2192', - 'Rightarrow;': '\u21d2', - 'rightarrow;': '\u2192', - 'RightArrowBar;': '\u21e5', - 'RightArrowLeftArrow;': '\u21c4', - 'rightarrowtail;': '\u21a3', - 'RightCeiling;': '\u2309', - 'RightDoubleBracket;': '\u27e7', - 'RightDownTeeVector;': '\u295d', - 'RightDownVector;': '\u21c2', - 'RightDownVectorBar;': '\u2955', - 'RightFloor;': '\u230b', - 'rightharpoondown;': '\u21c1', - 'rightharpoonup;': '\u21c0', - 'rightleftarrows;': '\u21c4', - 'rightleftharpoons;': '\u21cc', - 'rightrightarrows;': '\u21c9', - 'rightsquigarrow;': '\u219d', - 'RightTee;': '\u22a2', - 'RightTeeArrow;': '\u21a6', - 'RightTeeVector;': '\u295b', - 'rightthreetimes;': '\u22cc', - 'RightTriangle;': '\u22b3', - 'RightTriangleBar;': '\u29d0', - 'RightTriangleEqual;': '\u22b5', - 'RightUpDownVector;': '\u294f', - 'RightUpTeeVector;': '\u295c', - 'RightUpVector;': '\u21be', - 'RightUpVectorBar;': '\u2954', - 'RightVector;': '\u21c0', - 'RightVectorBar;': '\u2953', - 'ring;': '\u02da', - 'risingdotseq;': '\u2253', - 'rlarr;': '\u21c4', - 'rlhar;': '\u21cc', - 'rlm;': '\u200f', - 'rmoust;': '\u23b1', - 'rmoustache;': '\u23b1', - 'rnmid;': '\u2aee', - 'roang;': '\u27ed', - 'roarr;': '\u21fe', - 'robrk;': '\u27e7', - 'ropar;': '\u2986', - 'Ropf;': '\u211d', - 'ropf;': '\U0001d563', - 'roplus;': '\u2a2e', - 'rotimes;': '\u2a35', - 'RoundImplies;': '\u2970', - 'rpar;': ')', - 'rpargt;': '\u2994', - 'rppolint;': '\u2a12', - 'rrarr;': '\u21c9', - 'Rrightarrow;': '\u21db', - 'rsaquo;': '\u203a', - 'Rscr;': '\u211b', - 'rscr;': '\U0001d4c7', - 'Rsh;': '\u21b1', - 'rsh;': '\u21b1', - 'rsqb;': ']', - 'rsquo;': '\u2019', - 'rsquor;': '\u2019', - 'rthree;': '\u22cc', - 'rtimes;': '\u22ca', - 'rtri;': '\u25b9', - 'rtrie;': '\u22b5', - 'rtrif;': '\u25b8', - 'rtriltri;': '\u29ce', - 'RuleDelayed;': '\u29f4', - 'ruluhar;': '\u2968', - 'rx;': '\u211e', - 'Sacute;': '\u015a', - 'sacute;': '\u015b', - 'sbquo;': '\u201a', - 'Sc;': '\u2abc', - 'sc;': '\u227b', - 'scap;': '\u2ab8', - 'Scaron;': '\u0160', - 'scaron;': '\u0161', - 'sccue;': '\u227d', - 'scE;': '\u2ab4', - 'sce;': '\u2ab0', - 'Scedil;': '\u015e', - 'scedil;': '\u015f', - 'Scirc;': '\u015c', - 'scirc;': '\u015d', - 'scnap;': '\u2aba', - 'scnE;': '\u2ab6', - 'scnsim;': '\u22e9', - 'scpolint;': '\u2a13', - 'scsim;': '\u227f', - 'Scy;': '\u0421', - 'scy;': '\u0441', - 'sdot;': '\u22c5', - 'sdotb;': '\u22a1', - 'sdote;': '\u2a66', - 'searhk;': '\u2925', - 'seArr;': '\u21d8', - 'searr;': '\u2198', - 'searrow;': '\u2198', - 'sect': '\xa7', - 'sect;': '\xa7', - 'semi;': ';', - 'seswar;': '\u2929', - 'setminus;': '\u2216', - 'setmn;': '\u2216', - 'sext;': '\u2736', - 'Sfr;': '\U0001d516', - 'sfr;': '\U0001d530', - 'sfrown;': '\u2322', - 'sharp;': '\u266f', - 'SHCHcy;': '\u0429', - 'shchcy;': '\u0449', - 'SHcy;': '\u0428', - 'shcy;': '\u0448', - 'ShortDownArrow;': '\u2193', - 'ShortLeftArrow;': '\u2190', - 'shortmid;': '\u2223', - 'shortparallel;': '\u2225', - 'ShortRightArrow;': '\u2192', - 'ShortUpArrow;': '\u2191', - 'shy': '\xad', - 'shy;': '\xad', - 'Sigma;': '\u03a3', - 'sigma;': '\u03c3', - 'sigmaf;': '\u03c2', - 'sigmav;': '\u03c2', - 'sim;': '\u223c', - 'simdot;': '\u2a6a', - 'sime;': '\u2243', - 'simeq;': '\u2243', - 'simg;': '\u2a9e', - 'simgE;': '\u2aa0', - 'siml;': '\u2a9d', - 'simlE;': '\u2a9f', - 'simne;': '\u2246', - 'simplus;': '\u2a24', - 'simrarr;': '\u2972', - 'slarr;': '\u2190', - 'SmallCircle;': '\u2218', - 'smallsetminus;': '\u2216', - 'smashp;': '\u2a33', - 'smeparsl;': '\u29e4', - 'smid;': '\u2223', - 'smile;': '\u2323', - 'smt;': '\u2aaa', - 'smte;': '\u2aac', - 'smtes;': '\u2aac\ufe00', - 'SOFTcy;': '\u042c', - 'softcy;': '\u044c', - 'sol;': '/', - 'solb;': '\u29c4', - 'solbar;': '\u233f', - 'Sopf;': '\U0001d54a', - 'sopf;': '\U0001d564', - 'spades;': '\u2660', - 'spadesuit;': '\u2660', - 'spar;': '\u2225', - 'sqcap;': '\u2293', - 'sqcaps;': '\u2293\ufe00', - 'sqcup;': '\u2294', - 'sqcups;': '\u2294\ufe00', - 'Sqrt;': '\u221a', - 'sqsub;': '\u228f', - 'sqsube;': '\u2291', - 'sqsubset;': '\u228f', - 'sqsubseteq;': '\u2291', - 'sqsup;': '\u2290', - 'sqsupe;': '\u2292', - 'sqsupset;': '\u2290', - 'sqsupseteq;': '\u2292', - 'squ;': '\u25a1', - 'Square;': '\u25a1', - 'square;': '\u25a1', - 'SquareIntersection;': '\u2293', - 'SquareSubset;': '\u228f', - 'SquareSubsetEqual;': '\u2291', - 'SquareSuperset;': '\u2290', - 'SquareSupersetEqual;': '\u2292', - 'SquareUnion;': '\u2294', - 'squarf;': '\u25aa', - 'squf;': '\u25aa', - 'srarr;': '\u2192', - 'Sscr;': '\U0001d4ae', - 'sscr;': '\U0001d4c8', - 'ssetmn;': '\u2216', - 'ssmile;': '\u2323', - 'sstarf;': '\u22c6', - 'Star;': '\u22c6', - 'star;': '\u2606', - 'starf;': '\u2605', - 'straightepsilon;': '\u03f5', - 'straightphi;': '\u03d5', - 'strns;': '\xaf', - 'Sub;': '\u22d0', - 'sub;': '\u2282', - 'subdot;': '\u2abd', - 'subE;': '\u2ac5', - 'sube;': '\u2286', - 'subedot;': '\u2ac3', - 'submult;': '\u2ac1', - 'subnE;': '\u2acb', - 'subne;': '\u228a', - 'subplus;': '\u2abf', - 'subrarr;': '\u2979', - 'Subset;': '\u22d0', - 'subset;': '\u2282', - 'subseteq;': '\u2286', - 'subseteqq;': '\u2ac5', - 'SubsetEqual;': '\u2286', - 'subsetneq;': '\u228a', - 'subsetneqq;': '\u2acb', - 'subsim;': '\u2ac7', - 'subsub;': '\u2ad5', - 'subsup;': '\u2ad3', - 'succ;': '\u227b', - 'succapprox;': '\u2ab8', - 'succcurlyeq;': '\u227d', - 'Succeeds;': '\u227b', - 'SucceedsEqual;': '\u2ab0', - 'SucceedsSlantEqual;': '\u227d', - 'SucceedsTilde;': '\u227f', - 'succeq;': '\u2ab0', - 'succnapprox;': '\u2aba', - 'succneqq;': '\u2ab6', - 'succnsim;': '\u22e9', - 'succsim;': '\u227f', - 'SuchThat;': '\u220b', - 'Sum;': '\u2211', - 'sum;': '\u2211', - 'sung;': '\u266a', - 'sup1': '\xb9', - 'sup1;': '\xb9', - 'sup2': '\xb2', - 'sup2;': '\xb2', - 'sup3': '\xb3', - 'sup3;': '\xb3', - 'Sup;': '\u22d1', - 'sup;': '\u2283', - 'supdot;': '\u2abe', - 'supdsub;': '\u2ad8', - 'supE;': '\u2ac6', - 'supe;': '\u2287', - 'supedot;': '\u2ac4', - 'Superset;': '\u2283', - 'SupersetEqual;': '\u2287', - 'suphsol;': '\u27c9', - 'suphsub;': '\u2ad7', - 'suplarr;': '\u297b', - 'supmult;': '\u2ac2', - 'supnE;': '\u2acc', - 'supne;': '\u228b', - 'supplus;': '\u2ac0', - 'Supset;': '\u22d1', - 'supset;': '\u2283', - 'supseteq;': '\u2287', - 'supseteqq;': '\u2ac6', - 'supsetneq;': '\u228b', - 'supsetneqq;': '\u2acc', - 'supsim;': '\u2ac8', - 'supsub;': '\u2ad4', - 'supsup;': '\u2ad6', - 'swarhk;': '\u2926', - 'swArr;': '\u21d9', - 'swarr;': '\u2199', - 'swarrow;': '\u2199', - 'swnwar;': '\u292a', - 'szlig': '\xdf', - 'szlig;': '\xdf', - 'Tab;': '\t', - 'target;': '\u2316', - 'Tau;': '\u03a4', - 'tau;': '\u03c4', - 'tbrk;': '\u23b4', - 'Tcaron;': '\u0164', - 'tcaron;': '\u0165', - 'Tcedil;': '\u0162', - 'tcedil;': '\u0163', - 'Tcy;': '\u0422', - 'tcy;': '\u0442', - 'tdot;': '\u20db', - 'telrec;': '\u2315', - 'Tfr;': '\U0001d517', - 'tfr;': '\U0001d531', - 'there4;': '\u2234', - 'Therefore;': '\u2234', - 'therefore;': '\u2234', - 'Theta;': '\u0398', - 'theta;': '\u03b8', - 'thetasym;': '\u03d1', - 'thetav;': '\u03d1', - 'thickapprox;': '\u2248', - 'thicksim;': '\u223c', - 'ThickSpace;': '\u205f\u200a', - 'thinsp;': '\u2009', - 'ThinSpace;': '\u2009', - 'thkap;': '\u2248', - 'thksim;': '\u223c', - 'THORN': '\xde', - 'thorn': '\xfe', - 'THORN;': '\xde', - 'thorn;': '\xfe', - 'Tilde;': '\u223c', - 'tilde;': '\u02dc', - 'TildeEqual;': '\u2243', - 'TildeFullEqual;': '\u2245', - 'TildeTilde;': '\u2248', - 'times': '\xd7', - 'times;': '\xd7', - 'timesb;': '\u22a0', - 'timesbar;': '\u2a31', - 'timesd;': '\u2a30', - 'tint;': '\u222d', - 'toea;': '\u2928', - 'top;': '\u22a4', - 'topbot;': '\u2336', - 'topcir;': '\u2af1', - 'Topf;': '\U0001d54b', - 'topf;': '\U0001d565', - 'topfork;': '\u2ada', - 'tosa;': '\u2929', - 'tprime;': '\u2034', - 'TRADE;': '\u2122', - 'trade;': '\u2122', - 'triangle;': '\u25b5', - 'triangledown;': '\u25bf', - 'triangleleft;': '\u25c3', - 'trianglelefteq;': '\u22b4', - 'triangleq;': '\u225c', - 'triangleright;': '\u25b9', - 'trianglerighteq;': '\u22b5', - 'tridot;': '\u25ec', - 'trie;': '\u225c', - 'triminus;': '\u2a3a', - 'TripleDot;': '\u20db', - 'triplus;': '\u2a39', - 'trisb;': '\u29cd', - 'tritime;': '\u2a3b', - 'trpezium;': '\u23e2', - 'Tscr;': '\U0001d4af', - 'tscr;': '\U0001d4c9', - 'TScy;': '\u0426', - 'tscy;': '\u0446', - 'TSHcy;': '\u040b', - 'tshcy;': '\u045b', - 'Tstrok;': '\u0166', - 'tstrok;': '\u0167', - 'twixt;': '\u226c', - 'twoheadleftarrow;': '\u219e', - 'twoheadrightarrow;': '\u21a0', - 'Uacute': '\xda', - 'uacute': '\xfa', - 'Uacute;': '\xda', - 'uacute;': '\xfa', - 'Uarr;': '\u219f', - 'uArr;': '\u21d1', - 'uarr;': '\u2191', - 'Uarrocir;': '\u2949', - 'Ubrcy;': '\u040e', - 'ubrcy;': '\u045e', - 'Ubreve;': '\u016c', - 'ubreve;': '\u016d', - 'Ucirc': '\xdb', - 'ucirc': '\xfb', - 'Ucirc;': '\xdb', - 'ucirc;': '\xfb', - 'Ucy;': '\u0423', - 'ucy;': '\u0443', - 'udarr;': '\u21c5', - 'Udblac;': '\u0170', - 'udblac;': '\u0171', - 'udhar;': '\u296e', - 'ufisht;': '\u297e', - 'Ufr;': '\U0001d518', - 'ufr;': '\U0001d532', - 'Ugrave': '\xd9', - 'ugrave': '\xf9', - 'Ugrave;': '\xd9', - 'ugrave;': '\xf9', - 'uHar;': '\u2963', - 'uharl;': '\u21bf', - 'uharr;': '\u21be', - 'uhblk;': '\u2580', - 'ulcorn;': '\u231c', - 'ulcorner;': '\u231c', - 'ulcrop;': '\u230f', - 'ultri;': '\u25f8', - 'Umacr;': '\u016a', - 'umacr;': '\u016b', - 'uml': '\xa8', - 'uml;': '\xa8', - 'UnderBar;': '_', - 'UnderBrace;': '\u23df', - 'UnderBracket;': '\u23b5', - 'UnderParenthesis;': '\u23dd', - 'Union;': '\u22c3', - 'UnionPlus;': '\u228e', - 'Uogon;': '\u0172', - 'uogon;': '\u0173', - 'Uopf;': '\U0001d54c', - 'uopf;': '\U0001d566', - 'UpArrow;': '\u2191', - 'Uparrow;': '\u21d1', - 'uparrow;': '\u2191', - 'UpArrowBar;': '\u2912', - 'UpArrowDownArrow;': '\u21c5', - 'UpDownArrow;': '\u2195', - 'Updownarrow;': '\u21d5', - 'updownarrow;': '\u2195', - 'UpEquilibrium;': '\u296e', - 'upharpoonleft;': '\u21bf', - 'upharpoonright;': '\u21be', - 'uplus;': '\u228e', - 'UpperLeftArrow;': '\u2196', - 'UpperRightArrow;': '\u2197', - 'Upsi;': '\u03d2', - 'upsi;': '\u03c5', - 'upsih;': '\u03d2', - 'Upsilon;': '\u03a5', - 'upsilon;': '\u03c5', - 'UpTee;': '\u22a5', - 'UpTeeArrow;': '\u21a5', - 'upuparrows;': '\u21c8', - 'urcorn;': '\u231d', - 'urcorner;': '\u231d', - 'urcrop;': '\u230e', - 'Uring;': '\u016e', - 'uring;': '\u016f', - 'urtri;': '\u25f9', - 'Uscr;': '\U0001d4b0', - 'uscr;': '\U0001d4ca', - 'utdot;': '\u22f0', - 'Utilde;': '\u0168', - 'utilde;': '\u0169', - 'utri;': '\u25b5', - 'utrif;': '\u25b4', - 'uuarr;': '\u21c8', - 'Uuml': '\xdc', - 'uuml': '\xfc', - 'Uuml;': '\xdc', - 'uuml;': '\xfc', - 'uwangle;': '\u29a7', - 'vangrt;': '\u299c', - 'varepsilon;': '\u03f5', - 'varkappa;': '\u03f0', - 'varnothing;': '\u2205', - 'varphi;': '\u03d5', - 'varpi;': '\u03d6', - 'varpropto;': '\u221d', - 'vArr;': '\u21d5', - 'varr;': '\u2195', - 'varrho;': '\u03f1', - 'varsigma;': '\u03c2', - 'varsubsetneq;': '\u228a\ufe00', - 'varsubsetneqq;': '\u2acb\ufe00', - 'varsupsetneq;': '\u228b\ufe00', - 'varsupsetneqq;': '\u2acc\ufe00', - 'vartheta;': '\u03d1', - 'vartriangleleft;': '\u22b2', - 'vartriangleright;': '\u22b3', - 'Vbar;': '\u2aeb', - 'vBar;': '\u2ae8', - 'vBarv;': '\u2ae9', - 'Vcy;': '\u0412', - 'vcy;': '\u0432', - 'VDash;': '\u22ab', - 'Vdash;': '\u22a9', - 'vDash;': '\u22a8', - 'vdash;': '\u22a2', - 'Vdashl;': '\u2ae6', - 'Vee;': '\u22c1', - 'vee;': '\u2228', - 'veebar;': '\u22bb', - 'veeeq;': '\u225a', - 'vellip;': '\u22ee', - 'Verbar;': '\u2016', - 'verbar;': '|', - 'Vert;': '\u2016', - 'vert;': '|', - 'VerticalBar;': '\u2223', - 'VerticalLine;': '|', - 'VerticalSeparator;': '\u2758', - 'VerticalTilde;': '\u2240', - 'VeryThinSpace;': '\u200a', - 'Vfr;': '\U0001d519', - 'vfr;': '\U0001d533', - 'vltri;': '\u22b2', - 'vnsub;': '\u2282\u20d2', - 'vnsup;': '\u2283\u20d2', - 'Vopf;': '\U0001d54d', - 'vopf;': '\U0001d567', - 'vprop;': '\u221d', - 'vrtri;': '\u22b3', - 'Vscr;': '\U0001d4b1', - 'vscr;': '\U0001d4cb', - 'vsubnE;': '\u2acb\ufe00', - 'vsubne;': '\u228a\ufe00', - 'vsupnE;': '\u2acc\ufe00', - 'vsupne;': '\u228b\ufe00', - 'Vvdash;': '\u22aa', - 'vzigzag;': '\u299a', - 'Wcirc;': '\u0174', - 'wcirc;': '\u0175', - 'wedbar;': '\u2a5f', - 'Wedge;': '\u22c0', - 'wedge;': '\u2227', - 'wedgeq;': '\u2259', - 'weierp;': '\u2118', - 'Wfr;': '\U0001d51a', - 'wfr;': '\U0001d534', - 'Wopf;': '\U0001d54e', - 'wopf;': '\U0001d568', - 'wp;': '\u2118', - 'wr;': '\u2240', - 'wreath;': '\u2240', - 'Wscr;': '\U0001d4b2', - 'wscr;': '\U0001d4cc', - 'xcap;': '\u22c2', - 'xcirc;': '\u25ef', - 'xcup;': '\u22c3', - 'xdtri;': '\u25bd', - 'Xfr;': '\U0001d51b', - 'xfr;': '\U0001d535', - 'xhArr;': '\u27fa', - 'xharr;': '\u27f7', - 'Xi;': '\u039e', - 'xi;': '\u03be', - 'xlArr;': '\u27f8', - 'xlarr;': '\u27f5', - 'xmap;': '\u27fc', - 'xnis;': '\u22fb', - 'xodot;': '\u2a00', - 'Xopf;': '\U0001d54f', - 'xopf;': '\U0001d569', - 'xoplus;': '\u2a01', - 'xotime;': '\u2a02', - 'xrArr;': '\u27f9', - 'xrarr;': '\u27f6', - 'Xscr;': '\U0001d4b3', - 'xscr;': '\U0001d4cd', - 'xsqcup;': '\u2a06', - 'xuplus;': '\u2a04', - 'xutri;': '\u25b3', - 'xvee;': '\u22c1', - 'xwedge;': '\u22c0', - 'Yacute': '\xdd', - 'yacute': '\xfd', - 'Yacute;': '\xdd', - 'yacute;': '\xfd', - 'YAcy;': '\u042f', - 'yacy;': '\u044f', - 'Ycirc;': '\u0176', - 'ycirc;': '\u0177', - 'Ycy;': '\u042b', - 'ycy;': '\u044b', - 'yen': '\xa5', - 'yen;': '\xa5', - 'Yfr;': '\U0001d51c', - 'yfr;': '\U0001d536', - 'YIcy;': '\u0407', - 'yicy;': '\u0457', - 'Yopf;': '\U0001d550', - 'yopf;': '\U0001d56a', - 'Yscr;': '\U0001d4b4', - 'yscr;': '\U0001d4ce', - 'YUcy;': '\u042e', - 'yucy;': '\u044e', - 'yuml': '\xff', - 'Yuml;': '\u0178', - 'yuml;': '\xff', - 'Zacute;': '\u0179', - 'zacute;': '\u017a', - 'Zcaron;': '\u017d', - 'zcaron;': '\u017e', - 'Zcy;': '\u0417', - 'zcy;': '\u0437', - 'Zdot;': '\u017b', - 'zdot;': '\u017c', - 'zeetrf;': '\u2128', - 'ZeroWidthSpace;': '\u200b', - 'Zeta;': '\u0396', - 'zeta;': '\u03b6', - 'Zfr;': '\u2128', - 'zfr;': '\U0001d537', - 'ZHcy;': '\u0416', - 'zhcy;': '\u0436', - 'zigrarr;': '\u21dd', - 'Zopf;': '\u2124', - 'zopf;': '\U0001d56b', - 'Zscr;': '\U0001d4b5', - 'zscr;': '\U0001d4cf', - 'zwj;': '\u200d', - 'zwnj;': '\u200c', -} - -# maps the Unicode codepoint to the HTML entity name -codepoint2name = {} - -# maps the HTML entity name to the character -# (or a character reference if the character is outside the Latin-1 range) -entitydefs = {} - -for (name, codepoint) in name2codepoint.items(): - codepoint2name[codepoint] = name - entitydefs[name] = chr(codepoint) - -del name, codepoint diff --git a/html.entities/setup.py b/html.entities/setup.py deleted file mode 100644 index f37bea8ce..000000000 --- a/html.entities/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-html.entities', - version='3.3.3-1', - description='CPython html.entities module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['html']) diff --git a/html.parser/setup.py b/html.parser/setup.py deleted file mode 100644 index 149098666..000000000 --- a/html.parser/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-html.parser', - version='3.3.3-2', - description='CPython html.parser module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['html'], - install_requires=['micropython-_markupbase', 'micropython-warnings', 'micropython-html.entities', 'micropython-re-pcre']) diff --git a/html/setup.py b/html/setup.py deleted file mode 100644 index ad115404a..000000000 --- a/html/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-html', - version='3.3.3-2', - description='CPython html module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['html'], - install_requires=['micropython-string']) diff --git a/http.client/setup.py b/http.client/setup.py deleted file mode 100644 index d3eb1c897..000000000 --- a/http.client/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-http.client', - version='0.5.1', - description='CPython http.client module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['http'], - install_requires=['micropython-email.parser', 'micropython-email.message', 'micropython-socket', 'micropython-collections', 'micropython-urllib.parse', 'micropython-warnings']) diff --git a/imaplib/imaplib.py b/imaplib/imaplib.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/imaplib/metadata.txt b/imaplib/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/imaplib/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/imaplib/setup.py b/imaplib/setup.py deleted file mode 100644 index 8035d0d9a..000000000 --- a/imaplib/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-imaplib', - version='0.0.1', - description='Dummy imaplib module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['imaplib']) diff --git a/imp/imp.py b/imp/imp.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/imp/metadata.txt b/imp/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/imp/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/imp/setup.py b/imp/setup.py deleted file mode 100644 index 5d6c192ab..000000000 --- a/imp/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-imp', - version='0.0.1', - description='Dummy imp module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['imp']) diff --git a/importlib/importlib.py b/importlib/importlib.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/importlib/metadata.txt b/importlib/metadata.txt deleted file mode 100644 index 976088c8a..000000000 --- a/importlib/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.0 diff --git a/importlib/setup.py b/importlib/setup.py deleted file mode 100644 index ac28d4701..000000000 --- a/importlib/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-importlib', - version='0.0.0', - description='Dummy importlib module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['importlib']) diff --git a/inspect/setup.py b/inspect/setup.py deleted file mode 100644 index a1840944d..000000000 --- a/inspect/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-inspect', - version='0.1.2', - description='inspect module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['inspect']) diff --git a/io/setup.py b/io/setup.py deleted file mode 100644 index f32216e95..000000000 --- a/io/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-io', - version='0.1', - description='Dummy io module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['io']) diff --git a/ipaddress/ipaddress.py b/ipaddress/ipaddress.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/ipaddress/metadata.txt b/ipaddress/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/ipaddress/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/ipaddress/setup.py b/ipaddress/setup.py deleted file mode 100644 index 26aeed012..000000000 --- a/ipaddress/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-ipaddress', - version='0.0.1', - description='Dummy ipaddress module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['ipaddress']) diff --git a/itertools/setup.py b/itertools/setup.py deleted file mode 100644 index 603f84539..000000000 --- a/itertools/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-itertools', - version='0.2.3', - description='itertools module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['itertools']) diff --git a/json/setup.py b/json/setup.py deleted file mode 100644 index 994479261..000000000 --- a/json/setup.py +++ /dev/null @@ -1,16 +0,0 @@ -#import sys -# Remove current dir from sys.path, otherwise distutils will peek up our -# copy module instead of system. -#sys.path.pop(0) -from setuptools import setup - -setup(name='micropython-json', - version='0.1', - description='CPython json package ported to MicroPython', - url='https://github.com/micropython/micropython/issues/405', - author='CPython Developers', - maintainer='MicroPython Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - install_requires=['micropython-re-pcre'], - packages=['json']) diff --git a/linecache/linecache.py b/linecache/linecache.py deleted file mode 100644 index 039e6af9e..000000000 --- a/linecache/linecache.py +++ /dev/null @@ -1 +0,0 @@ -cache = {} diff --git a/linecache/metadata.txt b/linecache/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/linecache/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/linecache/setup.py b/linecache/setup.py deleted file mode 100644 index c1a9ba10c..000000000 --- a/linecache/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-linecache', - version='0.0.1', - description='Dummy linecache module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['linecache']) diff --git a/locale/metadata.txt b/locale/metadata.txt deleted file mode 100644 index fda992a9c..000000000 --- a/locale/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.2 diff --git a/locale/setup.py b/locale/setup.py deleted file mode 100644 index 05e2395f2..000000000 --- a/locale/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-locale', - version='0.0.2', - description='Dummy locale module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['locale']) diff --git a/logging/setup.py b/logging/setup.py deleted file mode 100644 index ea7f3eb44..000000000 --- a/logging/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-logging', - version='0.3', - description='logging module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['logging']) diff --git a/machine/setup.py b/machine/setup.py deleted file mode 100644 index 88fa27ba6..000000000 --- a/machine/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-machine', - version='0.2.1', - description='machine module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['machine'], - install_requires=['micropython-ffilib', 'micropython-os', 'micropython-signal']) diff --git a/mailbox/mailbox.py b/mailbox/mailbox.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/mailbox/metadata.txt b/mailbox/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/mailbox/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/mailbox/setup.py b/mailbox/setup.py deleted file mode 100644 index 389f27177..000000000 --- a/mailbox/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-mailbox', - version='0.0.1', - description='Dummy mailbox module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['mailbox']) diff --git a/mailcap/mailcap.py b/mailcap/mailcap.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/mailcap/metadata.txt b/mailcap/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/mailcap/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/mailcap/setup.py b/mailcap/setup.py deleted file mode 100644 index 7631904d7..000000000 --- a/mailcap/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-mailcap', - version='0.0.1', - description='Dummy mailcap module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['mailcap']) diff --git a/make_metadata.py b/make_metadata.py deleted file mode 100755 index 8c59c72eb..000000000 --- a/make_metadata.py +++ /dev/null @@ -1,178 +0,0 @@ -#!/usr/bin/env python3 -# MicroPython will pick up glob from the current dir otherwise. -import sys -sys.path.pop(0) - -import glob - - -TEMPLATE = """\ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-%(dist_name)s', - version='%(version)s', - description=%(desc)r, - long_description=%(long_desc)s, - url='https://github.com/micropython/micropython-lib', - author=%(author)r, - author_email=%(author_email)r, - maintainer=%(maintainer)r, - maintainer_email='micro-python@googlegroups.com', - license=%(license)r, - cmdclass={'sdist': sdist_upip.sdist}, - %(_what_)s=[%(modules)s]%(_inst_req_)s) -""" - -DUMMY_DESC = """\ -This is a dummy implementation of a module for MicroPython standard library. -It contains zero or very little functionality, and primarily intended to -avoid import errors (using idea that even if an application imports a -module, it may be not using it onevery code path, so may work at least -partially). It is expected that more complete implementation of the module -will be provided later. Please help with the development if you are -interested in this module.""" - -CPYTHON_DESC = """\ -This is a module ported from CPython standard library to be compatible with -MicroPython interpreter. Usually, this means applying small patches for -features not supported (yet, or at all) in MicroPython. Sometimes, heavier -changes are required. Note that CPython modules are written with availability -of vast resources in mind, and may not work for MicroPython ports with -limited heap. If you are affected by such a case, please help reimplement -the module from scratch.""" - -PYPY_DESC = """\ -This is a module ported from PyPy standard library to be compatible with -MicroPython interpreter. Usually, this means applying small patches for -features not supported (yet, or at all) in MicroPython. Sometimes, heavier -changes are required. Note that CPython modules are written with availability -of vast resources in mind, and may not work for MicroPython ports with -limited heap. If you are affected by such a case, please help reimplement -the module from scratch.""" - -MICROPYTHON_LIB_DESC = """\ -This is a module reimplemented specifically for MicroPython standard library, -with efficient and lean design in mind. Note that this module is likely work -in progress and likely supports just a subset of CPython's corresponding -module. Please help with the development if you are interested in this -module.""" - -BACKPORT_DESC = """\ -This is MicroPython compatibility module, allowing applications using -MicroPython-specific features to run on CPython. -""" - -MICROPYTHON_DEVELS = 'micropython-lib Developers' -MICROPYTHON_DEVELS_EMAIL = 'micro-python@googlegroups.com' -CPYTHON_DEVELS = 'CPython Developers' -CPYTHON_DEVELS_EMAIL = 'python-dev@python.org' -PYPY_DEVELS = 'PyPy Developers' -PYPY_DEVELS_EMAIL = 'pypy-dev@python.org' - -def parse_metadata(f): - data = {} - for l in f: - l = l.strip() - if l[0] == "#": - continue - k, v = l.split("=", 1) - data[k.strip()] = v.strip() - return data - - -def write_setup(fname, substs): - with open(fname, "w") as f: - f.write(TEMPLATE % substs) - - -def main(): - for fname in glob.iglob("*/metadata.txt"): - print(fname) - with open(fname) as f: - data = parse_metadata(f) - - dirname = fname.split("/")[0] - module = dirname - if data["type"] == "module": - data["_what_"] = "py_modules" - elif data["type"] == "package": - data["_what_"] = "packages" - else: - raise ValueError - - if data["srctype"] == "dummy": - data["author"] = MICROPYTHON_DEVELS - data["author_email"] = MICROPYTHON_DEVELS_EMAIL - data["maintainer"] = MICROPYTHON_DEVELS - data["license"] = "MIT" - data["desc"] = "Dummy %s module for MicroPython" % module - data["long_desc"] = DUMMY_DESC - elif data["srctype"] == "cpython": - data["author"] = CPYTHON_DEVELS - data["author_email"] = CPYTHON_DEVELS_EMAIL - data["maintainer"] = MICROPYTHON_DEVELS - data["license"] = "Python" - data["desc"] = "CPython %s module ported to MicroPython" % module - data["long_desc"] = CPYTHON_DESC - elif data["srctype"] == "pypy": - data["author"] = PYPY_DEVELS - data["author_email"] = PYPY_DEVELS_EMAIL - data["maintainer"] = MICROPYTHON_DEVELS - data["license"] = "MIT" - data["desc"] = "PyPy %s module ported to MicroPython" % module - data["long_desc"] = PYPY_DESC - elif data["srctype"] == "micropython-lib": - if "author" not in data: - data["author"] = MICROPYTHON_DEVELS - if "author_email" not in data: - data["author_email"] = MICROPYTHON_DEVELS_EMAIL - if "maintainer" not in data: - data["maintainer"] = MICROPYTHON_DEVELS - if "desc" not in data: - data["desc"] = "%s module for MicroPython" % module - if "long_desc" not in data: - data["long_desc"] = MICROPYTHON_LIB_DESC - if "license" not in data: - data["license"] = "MIT" - elif data["srctype"] == "cpython-backport": - assert module.startswith("cpython-") - module = module[len("cpython-"):] - data["author"] = MICROPYTHON_DEVELS - data["author_email"] = MICROPYTHON_DEVELS_EMAIL - data["maintainer"] = MICROPYTHON_DEVELS - data["license"] = "Python" - data["desc"] = "MicroPython module %s ported to CPython" % module - data["long_desc"] = BACKPORT_DESC - else: - raise ValueError - - if "dist_name" not in data: - data["dist_name"] = dirname - if "name" not in data: - data["name"] = module - if data["long_desc"] in ("README", "README.rst"): - data["long_desc"] = "open(%r).read()" % data["long_desc"] - else: - data["long_desc"] = repr(data["long_desc"]) - - data["modules"] = "'" + data["name"].rsplit(".", 1)[0] + "'" - if "extra_modules" in data: - data["modules"] += ", " + ", ".join(["'" + x.strip() + "'" for x in data["extra_modules"].split(",")]) - - if "depends" in data: - deps = ["micropython-" + x.strip() for x in data["depends"].split(",")] - data["_inst_req_"] = ",\n install_requires=['" + "', '".join(deps) + "']" - else: - data["_inst_req_"] = "" - - write_setup(dirname + "/setup.py", data) - - -if __name__ == "__main__": - main() diff --git a/math/metadata.txt b/math/metadata.txt deleted file mode 100644 index 976088c8a..000000000 --- a/math/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.0 diff --git a/math/setup.py b/math/setup.py deleted file mode 100644 index a2aab64c7..000000000 --- a/math/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-math', - version='0.0.0', - description='Dummy math module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['math']) diff --git a/micropython/README.md b/micropython/README.md new file mode 100644 index 000000000..2df5de466 --- /dev/null +++ b/micropython/README.md @@ -0,0 +1,13 @@ +MicroPython-specific libraries +============================== + +These are libraries that have been written specifically for use on MicroPython. + +In some cases, the libraries are inspired by or based on equivalent CPython standard libraries, but compatibility varies. The libraries are often named with a "u" prefix. + +Other libraries have been written specifically for MicroPython use cases. + +Future plans +------------ + +* More organised directory structure based on library purpose (e.g. drivers, network, etc). diff --git a/test.support/metadata.txt b/micropython/test.support/metadata.txt similarity index 100% rename from test.support/metadata.txt rename to micropython/test.support/metadata.txt diff --git a/micropython/test.support/setup.py b/micropython/test.support/setup.py new file mode 100644 index 000000000..e24879af7 --- /dev/null +++ b/micropython/test.support/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-test.support", + version="0.1.3", + description="test.support module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="micropython-lib Developers", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + packages=["test"], +) diff --git a/test.support/test/support.py b/micropython/test.support/test/support.py similarity index 98% rename from test.support/test/support.py rename to micropython/test.support/test/support.py index cc65613a3..435fa9224 100644 --- a/test.support/test/support.py +++ b/micropython/test.support/test/support.py @@ -5,7 +5,8 @@ import contextlib -TESTFN = '@test' +TESTFN = "@test" + def run_unittest(*classes): suite = unittest.TestSuite() @@ -21,18 +22,22 @@ def run_unittest(*classes): runner = unittest.TestRunner() result = runner.run(suite) + def can_symlink(): return False + def skip_unless_symlink(test): """Skip decorator for tests that require functional symlink""" ok = can_symlink() msg = "Requires functional symlink implementation" return test if ok else unittest.skip(msg)(test) + def create_empty_file(name): open(name, "w").close() + @contextlib.contextmanager def disable_gc(): have_gc = gc.isenabled() @@ -43,11 +48,13 @@ def disable_gc(): if have_gc: gc.enable() + def gc_collect(): gc.collect() gc.collect() gc.collect() + @contextlib.contextmanager def captured_output(stream_name): org = getattr(sys, stream_name) @@ -58,8 +65,10 @@ def captured_output(stream_name): finally: setattr(sys, stream_name, org) + def captured_stderr(): return captured_output("stderr") + def requires_IEEE_754(f): return f diff --git a/uaiohttpclient/README b/micropython/uaiohttpclient/README similarity index 100% rename from uaiohttpclient/README rename to micropython/uaiohttpclient/README diff --git a/uaiohttpclient/example.py b/micropython/uaiohttpclient/example.py similarity index 99% rename from uaiohttpclient/example.py rename to micropython/uaiohttpclient/example.py index e44dbb940..4134c7ee7 100644 --- a/uaiohttpclient/example.py +++ b/micropython/uaiohttpclient/example.py @@ -14,13 +14,16 @@ def print_stream(resp): break print(line.rstrip()) + def run(url): resp = yield from aiohttp.request("GET", url) print(resp) yield from print_stream(resp) + import sys import logging + logging.basicConfig(level=logging.INFO) url = sys.argv[1] loop = asyncio.get_event_loop() diff --git a/uaiohttpclient/metadata.txt b/micropython/uaiohttpclient/metadata.txt similarity index 100% rename from uaiohttpclient/metadata.txt rename to micropython/uaiohttpclient/metadata.txt diff --git a/micropython/uaiohttpclient/setup.py b/micropython/uaiohttpclient/setup.py new file mode 100644 index 000000000..86e7ac5b1 --- /dev/null +++ b/micropython/uaiohttpclient/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-uaiohttpclient", + version="0.5.1", + description="HTTP client module for MicroPython uasyncio module", + long_description=open("README").read(), + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["uaiohttpclient"], +) diff --git a/uaiohttpclient/uaiohttpclient.py b/micropython/uaiohttpclient/uaiohttpclient.py similarity index 89% rename from uaiohttpclient/uaiohttpclient.py rename to micropython/uaiohttpclient/uaiohttpclient.py index cf7fe19eb..25b2e62a9 100644 --- a/uaiohttpclient/uaiohttpclient.py +++ b/micropython/uaiohttpclient/uaiohttpclient.py @@ -2,7 +2,6 @@ class ClientResponse: - def __init__(self, reader): self.content = reader @@ -14,23 +13,22 @@ def __repr__(self): class ChunkedClientResponse(ClientResponse): - def __init__(self, reader): self.content = reader self.chunk_size = 0 - def read(self, sz=4*1024*1024): + def read(self, sz=4 * 1024 * 1024): if self.chunk_size == 0: l = yield from self.content.readline() - #print("chunk line:", l) + # print("chunk line:", l) l = l.split(b";", 1)[0] self.chunk_size = int(l, 16) - #print("chunk size:", self.chunk_size) + # print("chunk size:", self.chunk_size) if self.chunk_size == 0: # End of message sep = yield from self.content.read(2) assert sep == b"\r\n" - return b'' + return b"" data = yield from self.content.read(min(sz, self.chunk_size)) self.chunk_size -= len(data) if self.chunk_size == 0: @@ -54,9 +52,13 @@ def request_raw(method, url): # Use protocol 1.0, because 1.1 always allows to use chunked transfer-encoding # But explicitly set Connection: close, even though this should be default for 1.0, # because some servers misbehave w/o it. - query = "%s /%s HTTP/1.0\r\nHost: %s\r\nConnection: close\r\nUser-Agent: compat\r\n\r\n" % (method, path, host) - yield from writer.awrite(query.encode('latin-1')) -# yield from writer.aclose() + query = "%s /%s HTTP/1.0\r\nHost: %s\r\nConnection: close\r\nUser-Agent: compat\r\n\r\n" % ( + method, + path, + host, + ) + yield from writer.awrite(query.encode("latin-1")) + # yield from writer.aclose() return reader diff --git a/ucontextlib/metadata.txt b/micropython/ucontextlib/metadata.txt similarity index 100% rename from ucontextlib/metadata.txt rename to micropython/ucontextlib/metadata.txt diff --git a/micropython/ucontextlib/setup.py b/micropython/ucontextlib/setup.py new file mode 100644 index 000000000..aac090f6e --- /dev/null +++ b/micropython/ucontextlib/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-ucontextlib", + version="0.1.1", + description="ucontextlib module for MicroPython", + long_description="Minimal subset of contextlib for MicroPython low-memory ports", + url="https://github.com/micropython/micropython-lib", + author="micropython-lib Developers", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="Python", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["ucontextlib"], +) diff --git a/ucontextlib/tests.py b/micropython/ucontextlib/tests.py similarity index 73% rename from ucontextlib/tests.py rename to micropython/ucontextlib/tests.py index c5d29ecce..4fd026ae7 100644 --- a/ucontextlib/tests.py +++ b/micropython/ucontextlib/tests.py @@ -3,24 +3,23 @@ class ContextManagerTestCase(unittest.TestCase): - def setUp(self): self._history = [] @contextmanager def manager(x): - self._history.append('start') + self._history.append("start") try: yield x finally: - self._history.append('finish') + self._history.append("finish") self._manager = manager def test_context_manager(self): with self._manager(123) as x: self.assertEqual(x, 123) - self.assertEqual(self._history, ['start', 'finish']) + self.assertEqual(self._history, ["start", "finish"]) def test_context_manager_on_error(self): exc = Exception() @@ -29,8 +28,8 @@ def test_context_manager_on_error(self): raise exc except Exception as e: self.assertEqual(exc, e) - self.assertEqual(self._history, ['start', 'finish']) + self.assertEqual(self._history, ["start", "finish"]) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/ucontextlib/ucontextlib.py b/micropython/ucontextlib/ucontextlib.py similarity index 99% rename from ucontextlib/ucontextlib.py rename to micropython/ucontextlib/ucontextlib.py index 29445a028..d259f9b8f 100644 --- a/ucontextlib/ucontextlib.py +++ b/micropython/ucontextlib/ucontextlib.py @@ -9,6 +9,7 @@ - supress """ + class ContextDecorator(object): "A base class or mixin that enables context managers to work as decorators." @@ -28,6 +29,7 @@ def __call__(self, func): def inner(*args, **kwds): with self._recreate_cm(): return func(*args, **kwds) + return inner @@ -101,6 +103,8 @@ def some_generator(): """ + def helper(*args, **kwds): return _GeneratorContextManager(func, *args, **kwds) + return helper diff --git a/udnspkt/example_resolve.py b/micropython/udnspkt/example_resolve.py similarity index 100% rename from udnspkt/example_resolve.py rename to micropython/udnspkt/example_resolve.py diff --git a/udnspkt/metadata.txt b/micropython/udnspkt/metadata.txt similarity index 100% rename from udnspkt/metadata.txt rename to micropython/udnspkt/metadata.txt diff --git a/micropython/udnspkt/setup.py b/micropython/udnspkt/setup.py new file mode 100644 index 000000000..f0c8c0626 --- /dev/null +++ b/micropython/udnspkt/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-udnspkt", + version="0.1", + description="Make and parse DNS packets (Sans I/O approach).", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["udnspkt"], +) diff --git a/udnspkt/udnspkt.py b/micropython/udnspkt/udnspkt.py similarity index 81% rename from udnspkt/udnspkt.py rename to micropython/udnspkt/udnspkt.py index 4b798bf1f..e55285975 100644 --- a/udnspkt/udnspkt.py +++ b/micropython/udnspkt/udnspkt.py @@ -14,7 +14,7 @@ def skip_fqdn(buf): sz = buf.readbin("B") if not sz: break - if sz >= 0xc0: + if sz >= 0xC0: buf.readbin("B") break buf.read(sz) @@ -50,29 +50,29 @@ def parse_resp(buf, is_ipv6): acnt = buf.readbin(">H") nscnt = buf.readbin(">H") addcnt = buf.readbin(">H") - #print(qcnt, acnt, nscnt, addcnt) + # print(qcnt, acnt, nscnt, addcnt) skip_fqdn(buf) v = buf.readbin(">H") - #print(v) + # print(v) v = buf.readbin(">H") - #print(v) + # print(v) for i in range(acnt): - #print("Resp #%d" % i) - #v = read_fqdn(buf) - #print(v) + # print("Resp #%d" % i) + # v = read_fqdn(buf) + # print(v) skip_fqdn(buf) t = buf.readbin(">H") - #print("Type", t) + # print("Type", t) v = buf.readbin(">H") - #print("Class", v) + # print("Class", v) v = buf.readbin(">I") - #print("TTL", v) + # print("TTL", v) rlen = buf.readbin(">H") - #print("rlen", rlen) + # print("rlen", rlen) rval = buf.read(rlen) - #print(rval) + # print(rval) if t == typ: return rval diff --git a/umqtt.robust/README.rst b/micropython/umqtt.robust/README.rst similarity index 100% rename from umqtt.robust/README.rst rename to micropython/umqtt.robust/README.rst diff --git a/umqtt.robust/example_sub_robust.py b/micropython/umqtt.robust/example_sub_robust.py similarity index 100% rename from umqtt.robust/example_sub_robust.py rename to micropython/umqtt.robust/example_sub_robust.py diff --git a/umqtt.robust/metadata.txt b/micropython/umqtt.robust/metadata.txt similarity index 100% rename from umqtt.robust/metadata.txt rename to micropython/umqtt.robust/metadata.txt diff --git a/micropython/umqtt.robust/setup.py b/micropython/umqtt.robust/setup.py new file mode 100644 index 000000000..f0f23ed8c --- /dev/null +++ b/micropython/umqtt.robust/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-umqtt.robust", + version="1.0.1", + description='Lightweight MQTT client for MicroPython ("robust" version).', + long_description=open("README.rst").read(), + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + packages=["umqtt"], +) diff --git a/umqtt.robust/umqtt/robust.py b/micropython/umqtt.robust/umqtt/robust.py similarity index 99% rename from umqtt.robust/umqtt/robust.py rename to micropython/umqtt.robust/umqtt/robust.py index 7ee40e020..55dd4da13 100644 --- a/umqtt.robust/umqtt/robust.py +++ b/micropython/umqtt.robust/umqtt/robust.py @@ -1,6 +1,7 @@ import utime from . import simple + class MQTTClient(simple.MQTTClient): DELAY = 2 diff --git a/umqtt.simple/README.rst b/micropython/umqtt.simple/README.rst similarity index 100% rename from umqtt.simple/README.rst rename to micropython/umqtt.simple/README.rst diff --git a/umqtt.simple/example_pub.py b/micropython/umqtt.simple/example_pub.py similarity index 99% rename from umqtt.simple/example_pub.py rename to micropython/umqtt.simple/example_pub.py index c15d07642..082069cd4 100644 --- a/umqtt.simple/example_pub.py +++ b/micropython/umqtt.simple/example_pub.py @@ -3,11 +3,13 @@ # Test reception e.g. with: # mosquitto_sub -t foo_topic + def main(server="localhost"): c = MQTTClient("umqtt_client", server) c.connect() c.publish(b"foo_topic", b"hello") c.disconnect() + if __name__ == "__main__": main() diff --git a/umqtt.simple/example_pub_button.py b/micropython/umqtt.simple/example_pub_button.py similarity index 100% rename from umqtt.simple/example_pub_button.py rename to micropython/umqtt.simple/example_pub_button.py diff --git a/umqtt.simple/example_sub.py b/micropython/umqtt.simple/example_sub.py similarity index 99% rename from umqtt.simple/example_sub.py rename to micropython/umqtt.simple/example_sub.py index f08818488..890aa29b3 100644 --- a/umqtt.simple/example_sub.py +++ b/micropython/umqtt.simple/example_sub.py @@ -8,6 +8,7 @@ def sub_cb(topic, msg): print((topic, msg)) + def main(server="localhost"): c = MQTTClient("umqtt_client", server) c.set_callback(sub_cb) @@ -26,5 +27,6 @@ def main(server="localhost"): c.disconnect() + if __name__ == "__main__": main() diff --git a/umqtt.simple/example_sub_led.py b/micropython/umqtt.simple/example_sub_led.py similarity index 96% rename from umqtt.simple/example_sub_led.py rename to micropython/umqtt.simple/example_sub_led.py index d0f8132e1..73c6b58d8 100644 --- a/umqtt.simple/example_sub_led.py +++ b/micropython/umqtt.simple/example_sub_led.py @@ -17,6 +17,7 @@ state = 0 + def sub_cb(topic, msg): global state print((topic, msg)) @@ -43,7 +44,7 @@ def main(server=SERVER): try: while 1: - #micropython.mem_info() + # micropython.mem_info() c.wait_msg() finally: c.disconnect() diff --git a/umqtt.simple/metadata.txt b/micropython/umqtt.simple/metadata.txt similarity index 100% rename from umqtt.simple/metadata.txt rename to micropython/umqtt.simple/metadata.txt diff --git a/micropython/umqtt.simple/setup.py b/micropython/umqtt.simple/setup.py new file mode 100644 index 000000000..4da36993c --- /dev/null +++ b/micropython/umqtt.simple/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-umqtt.simple", + version="1.3.4", + description="Lightweight MQTT client for MicroPython.", + long_description=open("README.rst").read(), + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + packages=["umqtt"], +) diff --git a/umqtt.simple/umqtt/simple.py b/micropython/umqtt.simple/umqtt/simple.py similarity index 91% rename from umqtt.simple/umqtt/simple.py rename to micropython/umqtt.simple/umqtt/simple.py index 8216fa5e1..7910024f8 100644 --- a/umqtt.simple/umqtt/simple.py +++ b/micropython/umqtt.simple/umqtt/simple.py @@ -2,13 +2,23 @@ import ustruct as struct from ubinascii import hexlify + class MQTTException(Exception): pass -class MQTTClient: - def __init__(self, client_id, server, port=0, user=None, password=None, keepalive=0, - ssl=False, ssl_params={}): +class MQTTClient: + def __init__( + self, + client_id, + server, + port=0, + user=None, + password=None, + keepalive=0, + ssl=False, + ssl_params={}, + ): if port == 0: port = 8883 if ssl else 1883 self.client_id = client_id @@ -36,7 +46,7 @@ def _recv_len(self): sh = 0 while 1: b = self.sock.read(1)[0] - n |= (b & 0x7f) << sh + n |= (b & 0x7F) << sh if not b & 0x80: return n sh += 7 @@ -58,6 +68,7 @@ def connect(self, clean_session=True): self.sock.connect(addr) if self.ssl: import ussl + self.sock = ussl.wrap_socket(self.sock, **self.ssl_params) premsg = bytearray(b"\x10\0\0\0\0\0") msg = bytearray(b"\x04MQTT\x04\x02\0\0") @@ -77,15 +88,15 @@ def connect(self, clean_session=True): msg[6] |= self.lw_retain << 5 i = 1 - while sz > 0x7f: - premsg[i] = (sz & 0x7f) | 0x80 + while sz > 0x7F: + premsg[i] = (sz & 0x7F) | 0x80 sz >>= 7 i += 1 premsg[i] = sz self.sock.write(premsg, i + 2) self.sock.write(msg) - #print(hex(len(msg)), hexlify(msg, ":")) + # print(hex(len(msg)), hexlify(msg, ":")) self._send_str(self.client_id) if self.lw_topic: self._send_str(self.lw_topic) @@ -114,12 +125,12 @@ def publish(self, topic, msg, retain=False, qos=0): sz += 2 assert sz < 2097152 i = 1 - while sz > 0x7f: - pkt[i] = (sz & 0x7f) | 0x80 + while sz > 0x7F: + pkt[i] = (sz & 0x7F) | 0x80 sz >>= 7 i += 1 pkt[i] = sz - #print(hex(len(pkt)), hexlify(pkt, ":")) + # print(hex(len(pkt)), hexlify(pkt, ":")) self.sock.write(pkt, i + 1) self._send_str(topic) if qos > 0: @@ -146,7 +157,7 @@ def subscribe(self, topic, qos=0): pkt = bytearray(b"\x82\0\0\0") self.pid += 1 struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid) - #print(hex(len(pkt)), hexlify(pkt, ":")) + # print(hex(len(pkt)), hexlify(pkt, ":")) self.sock.write(pkt) self._send_str(topic) self.sock.write(qos.to_bytes(1, "little")) @@ -154,7 +165,7 @@ def subscribe(self, topic, qos=0): op = self.wait_msg() if op == 0x90: resp = self.sock.read(4) - #print(resp) + # print(resp) assert resp[1] == pkt[2] and resp[2] == pkt[3] if resp[3] == 0x80: raise MQTTException(resp[3]) @@ -176,7 +187,7 @@ def wait_msg(self): assert sz == 0 return None op = res[0] - if op & 0xf0 != 0x30: + if op & 0xF0 != 0x30: return op sz = self._recv_len() topic_len = self.sock.read(2) diff --git a/upip/Makefile b/micropython/upip/Makefile similarity index 100% rename from upip/Makefile rename to micropython/upip/Makefile diff --git a/upip/bootstrap_upip.sh b/micropython/upip/bootstrap_upip.sh similarity index 100% rename from upip/bootstrap_upip.sh rename to micropython/upip/bootstrap_upip.sh diff --git a/upip/metadata.txt b/micropython/upip/metadata.txt similarity index 100% rename from upip/metadata.txt rename to micropython/upip/metadata.txt diff --git a/micropython/upip/setup.py b/micropython/upip/setup.py new file mode 100644 index 000000000..5e8ff0b21 --- /dev/null +++ b/micropython/upip/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-upip", + version="1.2.4", + description="Simple package manager for MicroPython.", + long_description="Simple self-hosted package manager for MicroPython (requires usocket, ussl, uzlib, uctypes builtin modules). Compatible only with packages without custom setup.py code.", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["upip", "upip_utarfile"], +) diff --git a/upip/upip.py b/micropython/upip/upip.py similarity index 90% rename from upip/upip.py rename to micropython/upip/upip.py index a400c3174..b28fdfbb2 100644 --- a/upip/upip.py +++ b/micropython/upip/upip.py @@ -12,6 +12,7 @@ import ujson as json import uzlib import upip_utarfile as tarfile + gc.collect() @@ -22,9 +23,11 @@ file_buf = bytearray(512) + class NotFoundError(Exception): pass + def op_split(path): if path == "": return ("", "") @@ -36,9 +39,11 @@ def op_split(path): head = "/" return (head, r[1]) + def op_basename(path): return op_split(path)[1] + # Expects *file* name def _makedirs(name, mode=0o777): ret = False @@ -69,26 +74,27 @@ def save_file(fname, subf): break outf.write(file_buf, sz) + def install_tar(f, prefix): meta = {} for info in f: - #print(info) + # print(info) fname = info.name try: - fname = fname[fname.index("/") + 1:] + fname = fname[fname.index("/") + 1 :] except ValueError: fname = "" save = True for p in ("setup.", "PKG-INFO", "README"): - #print(fname, p) - if fname.startswith(p) or ".egg-info" in fname: - if fname.endswith("/requires.txt"): - meta["deps"] = f.extractfile(info).read() - save = False - if debug: - print("Skipping", fname) - break + # print(fname, p) + if fname.startswith(p) or ".egg-info" in fname: + if fname.endswith("/requires.txt"): + meta["deps"] = f.extractfile(info).read() + save = False + if debug: + print("Skipping", fname) + break if save: outfname = prefix + fname @@ -100,32 +106,37 @@ def install_tar(f, prefix): save_file(outfname, subf) return meta + def expandhome(s): if "~/" in s: h = os.getenv("HOME") s = s.replace("~/", h + "/") return s + import ussl import usocket + warn_ussl = True + + def url_open(url): global warn_ussl if debug: print(url) - proto, _, host, urlpath = url.split('/', 3) + proto, _, host, urlpath = url.split("/", 3) try: ai = usocket.getaddrinfo(host, 443, 0, usocket.SOCK_STREAM) except OSError as e: fatal("Unable to resolve %s (no Internet?)" % host, e) - #print("Address infos:", ai) + # print("Address infos:", ai) ai = ai[0] s = usocket.socket(ai[0], ai[1], ai[2]) try: - #print("Connect address:", addr) + # print("Connect address:", addr) s.connect(ai[-1]) if proto == "https:": @@ -146,7 +157,7 @@ def url_open(url): l = s.readline() if not l: raise ValueError("Unexpected EOF in HTTP headers") - if l == b'\r\n': + if l == b"\r\n": break except Exception as e: s.close() @@ -169,6 +180,7 @@ def fatal(msg, exc=None): raise exc sys.exit(1) + def install_pkg(pkg_spec, install_path): data = get_pkg_metadata(pkg_spec) @@ -192,6 +204,7 @@ def install_pkg(pkg_spec, install_path): gc.collect() return meta + def install(to_install, install_path=None): # Calculate gzip dictionary size to use global gzdict_sz @@ -224,9 +237,11 @@ def install(to_install, install_path=None): deps = deps.decode("utf-8").split("\n") to_install.extend(deps) except Exception as e: - print("Error installing '{}': {}, packages may be partially installed".format( - pkg_spec, e), - file=sys.stderr) + print( + "Error installing '{}': {}, packages may be partially installed".format(pkg_spec, e), + file=sys.stderr, + ) + def get_install_path(): global install_path @@ -236,6 +251,7 @@ def get_install_path(): install_path = expandhome(install_path) return install_path + def cleanup(): for fname in cleanup_files: try: @@ -243,21 +259,27 @@ def cleanup(): except OSError: print("Warning: Cannot delete " + fname) + def help(): - print("""\ + print( + """\ upip - Simple PyPI package manager for MicroPython Usage: micropython -m upip install [-p ] ... | -r import upip; upip.install(package_or_list, []) If is not given, packages will be installed into sys.path[1] (can be set from MICROPYPATH environment variable, if current system -supports that).""") +supports that).""" + ) print("Current value of sys.path[1]:", sys.path[1]) - print("""\ + print( + """\ Note: only MicroPython packages (usually, named micropython-*) are supported for installation, upip does not support arbitrary code in setup.py. -""") +""" + ) + def main(): global debug diff --git a/upip/upip_utarfile.py b/micropython/upip/upip_utarfile.py similarity index 71% rename from upip/upip_utarfile.py rename to micropython/upip/upip_utarfile.py index 460ca2cd4..21b899f02 100644 --- a/upip/upip_utarfile.py +++ b/micropython/upip/upip_utarfile.py @@ -9,11 +9,12 @@ DIRTYPE = "dir" REGTYPE = "file" + def roundup(val, align): return (val + align - 1) & ~(align - 1) -class FileSection: +class FileSection: def __init__(self, f, content_len, aligned_len): self.f = f self.content_len = content_len @@ -33,7 +34,7 @@ def readinto(self, buf): if self.content_len == 0: return 0 if len(buf) > self.content_len: - buf = memoryview(buf)[:self.content_len] + buf = memoryview(buf)[: self.content_len] sz = self.f.readinto(buf) self.content_len -= sz return sz @@ -47,13 +48,13 @@ def skip(self): self.f.readinto(buf, s) sz -= s -class TarInfo: +class TarInfo: def __str__(self): return "TarInfo(%r, %s, %d)" % (self.name, self.type, self.size) -class TarFile: +class TarFile: def __init__(self, name=None, fileobj=None): if fileobj: self.f = fileobj @@ -62,24 +63,24 @@ def __init__(self, name=None, fileobj=None): self.subf = None def next(self): - if self.subf: - self.subf.skip() - buf = self.f.read(512) - if not buf: - return None - - h = uctypes.struct(uctypes.addressof(buf), TAR_HEADER, uctypes.LITTLE_ENDIAN) - - # Empty block means end of archive - if h.name[0] == 0: - return None - - d = TarInfo() - d.name = str(h.name, "utf-8").rstrip("\0") - d.size = int(bytes(h.size), 8) - d.type = [REGTYPE, DIRTYPE][d.name[-1] == "/"] - self.subf = d.subf = FileSection(self.f, d.size, roundup(d.size, 512)) - return d + if self.subf: + self.subf.skip() + buf = self.f.read(512) + if not buf: + return None + + h = uctypes.struct(uctypes.addressof(buf), TAR_HEADER, uctypes.LITTLE_ENDIAN) + + # Empty block means end of archive + if h.name[0] == 0: + return None + + d = TarInfo() + d.name = str(h.name, "utf-8").rstrip("\0") + d.size = int(bytes(h.size), 8) + d.type = [REGTYPE, DIRTYPE][d.name[-1] == "/"] + self.subf = d.subf = FileSection(self.f, d.size, roundup(d.size, 512)) + return d def __iter__(self): return self diff --git a/upysh/metadata.txt b/micropython/upysh/metadata.txt similarity index 100% rename from upysh/metadata.txt rename to micropython/upysh/metadata.txt diff --git a/micropython/upysh/setup.py b/micropython/upysh/setup.py new file mode 100644 index 000000000..c1608d313 --- /dev/null +++ b/micropython/upysh/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-upysh", + version="0.6.1", + description="Minimalistic file shell using native Python syntax.", + long_description="Minimalistic file shell using native Python syntax.", + url="https://github.com/micropython/micropython-lib", + author="micropython-lib Developers", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["upysh"], +) diff --git a/upysh/upysh.py b/micropython/upysh/upysh.py similarity index 94% rename from upysh/upysh.py rename to micropython/upysh/upysh.py index 250c5747b..e46d395c9 100644 --- a/upysh/upysh.py +++ b/micropython/upysh/upysh.py @@ -1,8 +1,8 @@ import sys import os -class LS: +class LS: def __repr__(self): self.__call__() return "" @@ -17,14 +17,15 @@ def __call__(self, path="."): else: print("% 8d %s" % (st[6], f)) -class PWD: +class PWD: def __repr__(self): return os.getcwd() def __call__(self): return self.__repr__() + class CLEAR: def __repr__(self): return "\x1b[2J\x1b[H" @@ -43,16 +44,20 @@ def __call__(self): rm = os.remove rmdir = os.rmdir + def head(f, n=10): with open(f) as f: for i in range(n): l = f.readline() - if not l: break + if not l: + break sys.stdout.write(l) + def cat(f): head(f, 1 << 30) + def newfile(path): print("Type file contents line by line, finish with EOF (Ctrl+D).") with open(path, "w") as f: @@ -64,10 +69,10 @@ def newfile(path): f.write(l) f.write("\n") -class Man(): +class Man: def __repr__(self): - return(""" + return """ upysh is intended to be imported using: from upysh import * @@ -77,7 +82,8 @@ def __repr__(self): pwd, cd("new_dir"), ls, ls(...), head(...), cat(...) newfile(...), mv("old", "new"), rm(...), mkdir(...), rmdir(...), clear -""") +""" + man = Man() diff --git a/urllib.urequest/metadata.txt b/micropython/urllib.urequest/metadata.txt similarity index 100% rename from urllib.urequest/metadata.txt rename to micropython/urllib.urequest/metadata.txt diff --git a/micropython/urllib.urequest/setup.py b/micropython/urllib.urequest/setup.py new file mode 100644 index 000000000..5652f54b5 --- /dev/null +++ b/micropython/urllib.urequest/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-urllib.urequest", + version="0.6", + description="urllib.urequest module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + packages=["urllib"], +) diff --git a/urllib.urequest/urllib/urequest.py b/micropython/urllib.urequest/urllib/urequest.py similarity index 97% rename from urllib.urequest/urllib/urequest.py rename to micropython/urllib.urequest/urllib/urequest.py index fd52721b7..4c654d45e 100644 --- a/urllib.urequest/urllib/urequest.py +++ b/micropython/urllib.urequest/urllib/urequest.py @@ -1,5 +1,6 @@ import usocket + def urlopen(url, data=None, method="GET"): if data is not None and method == "GET": method = "POST" @@ -12,6 +13,7 @@ def urlopen(url, data=None, method="GET"): port = 80 elif proto == "https:": import ussl + port = 443 else: raise ValueError("Unsupported protocol: " + proto) @@ -46,13 +48,13 @@ def urlopen(url, data=None, method="GET"): l = s.readline() l = l.split(None, 2) - #print(l) + # print(l) status = int(l[1]) while True: l = s.readline() if not l or l == b"\r\n": break - #print(l) + # print(l) if l.startswith(b"Transfer-Encoding:"): if b"chunked" in l: raise ValueError("Unsupported " + l) diff --git a/utarfile/example-extract.py b/micropython/utarfile/example-extract.py similarity index 100% rename from utarfile/example-extract.py rename to micropython/utarfile/example-extract.py diff --git a/utarfile/metadata.txt b/micropython/utarfile/metadata.txt similarity index 100% rename from utarfile/metadata.txt rename to micropython/utarfile/metadata.txt diff --git a/micropython/utarfile/setup.py b/micropython/utarfile/setup.py new file mode 100644 index 000000000..a3d8a862e --- /dev/null +++ b/micropython/utarfile/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-utarfile", + version="0.3.2", + description="utarfile module for MicroPython", + long_description="Lightweight tarfile module subset", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["utarfile"], +) diff --git a/utarfile/utarfile.py b/micropython/utarfile/utarfile.py similarity index 71% rename from utarfile/utarfile.py rename to micropython/utarfile/utarfile.py index 460ca2cd4..21b899f02 100644 --- a/utarfile/utarfile.py +++ b/micropython/utarfile/utarfile.py @@ -9,11 +9,12 @@ DIRTYPE = "dir" REGTYPE = "file" + def roundup(val, align): return (val + align - 1) & ~(align - 1) -class FileSection: +class FileSection: def __init__(self, f, content_len, aligned_len): self.f = f self.content_len = content_len @@ -33,7 +34,7 @@ def readinto(self, buf): if self.content_len == 0: return 0 if len(buf) > self.content_len: - buf = memoryview(buf)[:self.content_len] + buf = memoryview(buf)[: self.content_len] sz = self.f.readinto(buf) self.content_len -= sz return sz @@ -47,13 +48,13 @@ def skip(self): self.f.readinto(buf, s) sz -= s -class TarInfo: +class TarInfo: def __str__(self): return "TarInfo(%r, %s, %d)" % (self.name, self.type, self.size) -class TarFile: +class TarFile: def __init__(self, name=None, fileobj=None): if fileobj: self.f = fileobj @@ -62,24 +63,24 @@ def __init__(self, name=None, fileobj=None): self.subf = None def next(self): - if self.subf: - self.subf.skip() - buf = self.f.read(512) - if not buf: - return None - - h = uctypes.struct(uctypes.addressof(buf), TAR_HEADER, uctypes.LITTLE_ENDIAN) - - # Empty block means end of archive - if h.name[0] == 0: - return None - - d = TarInfo() - d.name = str(h.name, "utf-8").rstrip("\0") - d.size = int(bytes(h.size), 8) - d.type = [REGTYPE, DIRTYPE][d.name[-1] == "/"] - self.subf = d.subf = FileSection(self.f, d.size, roundup(d.size, 512)) - return d + if self.subf: + self.subf.skip() + buf = self.f.read(512) + if not buf: + return None + + h = uctypes.struct(uctypes.addressof(buf), TAR_HEADER, uctypes.LITTLE_ENDIAN) + + # Empty block means end of archive + if h.name[0] == 0: + return None + + d = TarInfo() + d.name = str(h.name, "utf-8").rstrip("\0") + d.size = int(bytes(h.size), 8) + d.type = [REGTYPE, DIRTYPE][d.name[-1] == "/"] + self.subf = d.subf = FileSection(self.f, d.size, roundup(d.size, 512)) + return d def __iter__(self): return self diff --git a/xmltok/metadata.txt b/micropython/xmltok/metadata.txt similarity index 100% rename from xmltok/metadata.txt rename to micropython/xmltok/metadata.txt diff --git a/micropython/xmltok/setup.py b/micropython/xmltok/setup.py new file mode 100644 index 000000000..8b8b237c0 --- /dev/null +++ b/micropython/xmltok/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-xmltok", + version="0.2", + description="xmltok module for MicroPython", + long_description="Simple XML tokenizer", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["xmltok"], +) diff --git a/xmltok/test.xml b/micropython/xmltok/test.xml similarity index 100% rename from xmltok/test.xml rename to micropython/xmltok/test.xml diff --git a/micropython/xmltok/test_xmltok.py b/micropython/xmltok/test_xmltok.py new file mode 100644 index 000000000..98ec0d114 --- /dev/null +++ b/micropython/xmltok/test_xmltok.py @@ -0,0 +1,25 @@ +import xmltok + +expected = [ + ("PI", "xml"), + ("ATTR", ("", "version"), "1.0"), + ("START_TAG", ("s", "Envelope")), + ("ATTR", ("xmlns", "s"), "http://schemas.xmlsoap.org/soap/envelope/"), + ("ATTR", ("s", "encodingStyle"), "http://schemas.xmlsoap.org/soap/encoding/"), + ("START_TAG", ("s", "Body")), + ("START_TAG", ("u", "GetConnectionTypeInfo")), + ("ATTR", ("xmlns", "u"), "urn:schemas-upnp-org:service:WANIPConnection:1"), + ("TEXT", "foo bar\n baz\n \n"), + ("END_TAG", ("u", "GetConnectionTypeInfo")), + ("END_TAG", ("s", "Body")), + ("END_TAG", ("s", "Envelope")), +] + +dir = "." +if "/" in __file__: + dir = __file__.rsplit("/", 1)[0] + +ex = iter(expected) +for i in xmltok.tokenize(open(dir + "/test.xml")): + # print(i) + assert i == next(ex) diff --git a/xmltok/xmltok.py b/micropython/xmltok/xmltok.py similarity index 93% rename from xmltok/xmltok.py rename to micropython/xmltok/xmltok.py index c46f2bd42..53435d073 100644 --- a/xmltok/xmltok.py +++ b/micropython/xmltok/xmltok.py @@ -1,17 +1,18 @@ TEXT = "TEXT" START_TAG = "START_TAG" -#START_TAG_DONE = "START_TAG_DONE" +# START_TAG_DONE = "START_TAG_DONE" END_TAG = "END_TAG" PI = "PI" -#PI_DONE = "PI_DONE" +# PI_DONE = "PI_DONE" ATTR = "ATTR" -#ATTR_VAL = "ATTR_VAL" +# ATTR_VAL = "ATTR_VAL" + class XMLSyntaxError(Exception): pass -class XMLTokenizer: +class XMLTokenizer: def __init__(self, f): self.f = f self.nextch() @@ -46,7 +47,7 @@ def getident(self): ident = "" while True: c = self.curch() - if not(c.isalpha() or c.isdigit() or c in "_-."): + if not (c.isalpha() or c.isdigit() or c in "_-."): break ident += self.getch() return ident @@ -74,13 +75,13 @@ def expect(self, c): def lex_attrs_till(self): while self.isident(): attr = self.getnsident() - #yield (ATTR, attr) + # yield (ATTR, attr) self.expect("=") self.expect('"') val = "" while self.curch() != '"': val += self.getch() - #yield (ATTR_VAL, val) + # yield (ATTR_VAL, val) self.expect('"') yield (ATTR, attr, val) @@ -98,7 +99,7 @@ def tokenize(self): elif self.match("!"): self.expect("-") self.expect("-") - last3 = '' + last3 = "" while True: last3 = last3[-2:] + self.getch() if last3 == "-->": @@ -123,6 +124,7 @@ def gfind(gen, pred): if pred(i): return i + def text_of(gen, tag): # Return text content of a leaf tag def match_tag(t): @@ -138,5 +140,6 @@ def match_tag(t): assert t == TEXT return val + def tokenize(file): return XMLTokenizer(file).tokenize() diff --git a/mimetypes/metadata.txt b/mimetypes/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/mimetypes/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/mimetypes/mimetypes.py b/mimetypes/mimetypes.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/mimetypes/setup.py b/mimetypes/setup.py deleted file mode 100644 index eb02b3f2e..000000000 --- a/mimetypes/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-mimetypes', - version='0.0.1', - description='Dummy mimetypes module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['mimetypes']) diff --git a/multiprocessing/setup.py b/multiprocessing/setup.py deleted file mode 100644 index 9d7d8d743..000000000 --- a/multiprocessing/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-multiprocessing', - version='0.1.2', - description='multiprocessing module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['multiprocessing'], - install_requires=['micropython-os', 'micropython-select', 'micropython-pickle']) diff --git a/multiprocessing/test_process.py b/multiprocessing/test_process.py deleted file mode 100644 index d4b145174..000000000 --- a/multiprocessing/test_process.py +++ /dev/null @@ -1,9 +0,0 @@ -from multiprocessing import Process - -def f(name): - assert name == 'bob' - -if __name__ == '__main__': - p = Process(target=f, args=('bob',)) - p.start() - p.join() diff --git a/nntplib/metadata.txt b/nntplib/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/nntplib/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/nntplib/nntplib.py b/nntplib/nntplib.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/nntplib/setup.py b/nntplib/setup.py deleted file mode 100644 index f6bcd3038..000000000 --- a/nntplib/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-nntplib', - version='0.0.1', - description='Dummy nntplib module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['nntplib']) diff --git a/numbers/metadata.txt b/numbers/metadata.txt deleted file mode 100644 index fda992a9c..000000000 --- a/numbers/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.2 diff --git a/numbers/numbers.py b/numbers/numbers.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/numbers/setup.py b/numbers/setup.py deleted file mode 100644 index d2cd04b08..000000000 --- a/numbers/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-numbers', - version='0.0.2', - description='Dummy numbers module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['numbers']) diff --git a/operator/setup.py b/operator/setup.py deleted file mode 100644 index e40118a0d..000000000 --- a/operator/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-operator', - version='0.1.1', - description='operator module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['operator']) diff --git a/optimize_upip.py b/optimize_upip.py deleted file mode 100644 index 69d4ea6fb..000000000 --- a/optimize_upip.py +++ /dev/null @@ -1,121 +0,0 @@ -# -# This script optimizes a Python source distribution tarball as produced by -# "python3 setup.py sdist" command for MicroPython's native package manager, -# upip. Optimization includes: -# * Removing metadata files not used by upip (this includes setup.py) -# * Recompressing gzip archive with 4K dictionary size so it can be -# installed even on low-heap targets. -# -import sys -import os -import zlib -from subprocess import Popen, PIPE -import glob -import tarfile -import re -import io - - -def gzip_4k(inf, fname): - comp = zlib.compressobj(level=9, wbits=16 + 12) - with open(fname + ".out", "wb") as outf: - while 1: - data = inf.read(1024) - if not data: - break - outf.write(comp.compress(data)) - outf.write(comp.flush()) - os.rename(fname, fname + ".orig") - os.rename(fname + ".out", fname) - - -def recompress(fname): - with Popen(["gzip", "-d", "-c", fname], stdout=PIPE).stdout as inf: - gzip_4k(inf, fname) - -def find_latest(dir): - res = [] - for fname in glob.glob(dir + "/*.gz"): - st = os.stat(fname) - res.append((st.st_mtime, fname)) - res.sort() - latest = res[-1][1] - return latest - - -def recompress_latest(dir): - latest = find_latest(dir) - print(latest) - recompress(latest) - - -FILTERS = [ - # include, exclude, repeat - (r".+\.egg-info/(PKG-INFO|requires\.txt)", r"setup.py$"), - (r".+\.py$", r"[^/]+$"), - (None, r".+\.egg-info/.+"), -] - - -outbuf = io.BytesIO() - -def filter_tar(name): - fin = tarfile.open(name, "r:gz") - fout = tarfile.open(fileobj=outbuf, mode="w") - for info in fin: -# print(info) - if not "/" in info.name: - continue - fname = info.name.split("/", 1)[1] - include = None - - for inc_re, exc_re in FILTERS: - if include is None and inc_re: - if re.match(inc_re, fname): - include = True - - if include is None and exc_re: - if re.match(exc_re, fname): - include = False - - if include is None: - include = True - - if include: - print("Including:", fname) - else: - print("Excluding:", fname) - continue - - farch = fin.extractfile(info) - fout.addfile(info, farch) - fout.close() - fin.close() - - - -from setuptools import Command - -class OptimizeUpip(Command): - - user_options = [] - - def run(self): - latest = find_latest("dist") - filter_tar(latest) - outbuf.seek(0) - gzip_4k(outbuf, latest) - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - -# For testing only -if __name__ == "__main__": -# recompress_latest(sys.argv[1]) - filter_tar(sys.argv[1]) - outbuf.seek(0) - gzip_4k(outbuf, sys.argv[1]) diff --git a/optparse/metadata.txt b/optparse/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/optparse/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/optparse/optparse.py b/optparse/optparse.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/optparse/setup.py b/optparse/setup.py deleted file mode 100644 index 3223d7fb1..000000000 --- a/optparse/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-optparse', - version='0.0.1', - description='Dummy optparse module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['optparse']) diff --git a/os.path/setup.py b/os.path/setup.py deleted file mode 100644 index 9a00e3a19..000000000 --- a/os.path/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-os.path', - version='0.1.3', - description='os.path module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['os']) diff --git a/os/setup.py b/os/setup.py deleted file mode 100644 index afeb34763..000000000 --- a/os/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-os', - version='0.6', - description='os module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['os'], - install_requires=['micropython-ffilib', 'micropython-errno', 'micropython-stat']) diff --git a/pathlib/metadata.txt b/pathlib/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/pathlib/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/pathlib/pathlib.py b/pathlib/pathlib.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/pathlib/setup.py b/pathlib/setup.py deleted file mode 100644 index de14368ae..000000000 --- a/pathlib/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-pathlib', - version='0.0.1', - description='Dummy pathlib module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['pathlib']) diff --git a/pdb/metadata.txt b/pdb/metadata.txt deleted file mode 100644 index fda992a9c..000000000 --- a/pdb/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.2 diff --git a/pdb/pdb.py b/pdb/pdb.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/pdb/setup.py b/pdb/setup.py deleted file mode 100644 index 034247497..000000000 --- a/pdb/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-pdb', - version='0.0.2', - description='Dummy pdb module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['pdb']) diff --git a/pickle/setup.py b/pickle/setup.py deleted file mode 100644 index 7b85ac3f3..000000000 --- a/pickle/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-pickle', - version='0.1', - description='Dummy pickle module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['pickle']) diff --git a/pickletools/metadata.txt b/pickletools/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/pickletools/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/pickletools/pickletools.py b/pickletools/pickletools.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/pickletools/setup.py b/pickletools/setup.py deleted file mode 100644 index ecc13a6e9..000000000 --- a/pickletools/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-pickletools', - version='0.0.1', - description='Dummy pickletools module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['pickletools']) diff --git a/pkg_resources/setup.py b/pkg_resources/setup.py deleted file mode 100644 index 0c9de2668..000000000 --- a/pkg_resources/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-pkg_resources', - version='0.2.1', - description='pkg_resources module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['pkg_resources']) diff --git a/pkgutil/setup.py b/pkgutil/setup.py deleted file mode 100644 index 29dfb5c7d..000000000 --- a/pkgutil/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-pkgutil', - version='0.1.1', - description='pkgutil module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['pkgutil'], - install_requires=['micropython-pkg_resources']) diff --git a/platform/metadata.txt b/platform/metadata.txt deleted file mode 100644 index fda992a9c..000000000 --- a/platform/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.2 diff --git a/platform/platform.py b/platform/platform.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/platform/setup.py b/platform/setup.py deleted file mode 100644 index fb5bb2f4d..000000000 --- a/platform/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-platform', - version='0.0.2', - description='Dummy platform module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['platform']) diff --git a/poplib/metadata.txt b/poplib/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/poplib/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/poplib/poplib.py b/poplib/poplib.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/poplib/setup.py b/poplib/setup.py deleted file mode 100644 index 81db5c5c2..000000000 --- a/poplib/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-poplib', - version='0.0.1', - description='Dummy poplib module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['poplib']) diff --git a/posixpath/metadata.txt b/posixpath/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/posixpath/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/posixpath/posixpath.py b/posixpath/posixpath.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/posixpath/setup.py b/posixpath/setup.py deleted file mode 100644 index 4f0d141a7..000000000 --- a/posixpath/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-posixpath', - version='0.0.1', - description='Dummy posixpath module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['posixpath']) diff --git a/pprint/setup.py b/pprint/setup.py deleted file mode 100644 index dc314441f..000000000 --- a/pprint/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-pprint', - version='0.0.4', - description='Dummy pprint module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['pprint']) diff --git a/profile/metadata.txt b/profile/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/profile/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/profile/profile.py b/profile/profile.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/profile/setup.py b/profile/setup.py deleted file mode 100644 index 0004cf32a..000000000 --- a/profile/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-profile', - version='0.0.1', - description='Dummy profile module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['profile']) diff --git a/pty/metadata.txt b/pty/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/pty/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/pty/pty.py b/pty/pty.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/pty/setup.py b/pty/setup.py deleted file mode 100644 index 8d11adc5f..000000000 --- a/pty/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-pty', - version='0.0.1', - description='Dummy pty module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['pty']) diff --git a/pwd/setup.py b/pwd/setup.py deleted file mode 100644 index 7e6af95b3..000000000 --- a/pwd/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-pwd', - version='0.1', - description='pwd module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Riccardo Magliocchetti', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['pwd'], - install_requires=['micropython-ffilib']) diff --git a/pystone/setup.py b/pystone/setup.py deleted file mode 100644 index 6bf216af6..000000000 --- a/pystone/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-pystone', - version='3.4.2-2', - description='CPython pystone module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['pystone']) diff --git a/pystone_lowmem/setup.py b/pystone_lowmem/setup.py deleted file mode 100644 index 878342f4b..000000000 --- a/pystone_lowmem/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-pystone_lowmem', - version='3.4.2-4', - description='CPython pystone_lowmem module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['pystone_lowmem']) diff --git a/urequests/example_xively.py b/python-ecosys/urequests/example_xively.py similarity index 100% rename from urequests/example_xively.py rename to python-ecosys/urequests/example_xively.py diff --git a/urequests/metadata.txt b/python-ecosys/urequests/metadata.txt similarity index 100% rename from urequests/metadata.txt rename to python-ecosys/urequests/metadata.txt diff --git a/python-ecosys/urequests/setup.py b/python-ecosys/urequests/setup.py new file mode 100644 index 000000000..65ee5da8b --- /dev/null +++ b/python-ecosys/urequests/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-urequests", + version="0.6", + description="urequests module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["urequests"], +) diff --git a/urequests/urequests.py b/python-ecosys/urequests/urequests.py similarity index 98% rename from urequests/urequests.py rename to python-ecosys/urequests/urequests.py index acb220e85..75a145702 100644 --- a/urequests/urequests.py +++ b/python-ecosys/urequests/urequests.py @@ -1,7 +1,7 @@ import usocket -class Response: +class Response: def __init__(self, f): self.raw = f self.encoding = "utf-8" @@ -29,6 +29,7 @@ def text(self): def json(self): import ujson + return ujson.loads(self.content) @@ -42,6 +43,7 @@ def request(method, url, data=None, json=None, headers={}, stream=None): port = 80 elif proto == "https:": import ussl + port = 443 else: raise ValueError("Unsupported protocol: " + proto) @@ -70,6 +72,7 @@ def request(method, url, data=None, json=None, headers={}, stream=None): if json is not None: assert data is None import ujson + data = ujson.dumps(json) s.write(b"Content-Type: application/json\r\n") if data: @@ -79,7 +82,7 @@ def request(method, url, data=None, json=None, headers={}, stream=None): s.write(data) l = s.readline() - #print(l) + # print(l) l = l.split(None, 2) status = int(l[1]) reason = "" @@ -89,7 +92,7 @@ def request(method, url, data=None, json=None, headers={}, stream=None): l = s.readline() if not l or l == b"\r\n": break - #print(l) + # print(l) if l.startswith(b"Transfer-Encoding:"): if b"chunked" in l: raise ValueError("Unsupported " + l) @@ -108,17 +111,22 @@ def request(method, url, data=None, json=None, headers={}, stream=None): def head(url, **kw): return request("HEAD", url, **kw) + def get(url, **kw): return request("GET", url, **kw) + def post(url, **kw): return request("POST", url, **kw) + def put(url, **kw): return request("PUT", url, **kw) + def patch(url, **kw): return request("PATCH", url, **kw) + def delete(url, **kw): return request("DELETE", url, **kw) diff --git a/python-stdlib/README.md b/python-stdlib/README.md new file mode 100644 index 000000000..604e66fea --- /dev/null +++ b/python-stdlib/README.md @@ -0,0 +1,22 @@ +CPython standard libraries +========================== + +The libraries in this directory aim to provide compatible implementations of +standard libraries to allow existing Python code to run un-modified on +MicroPython. + +Implementation +-------------- + +Many libraries are implemented in pure Python, often based on the original +CPython implementation. (e.g. `collections.defaultdict`) + +Some libraries are based on or extend from the built-in "micro" modules in the +MicroPython firmware, providing additional functionality that didn't need to +be written in C (e.g. `collections`, `socket`, `struct`). + + +Future plans (ideas for contributors): +-------------------------------------- + +* Add README.md to each library explaining compatibility and limitations. diff --git a/__future__/__future__.py b/python-stdlib/__future__/__future__.py similarity index 100% rename from __future__/__future__.py rename to python-stdlib/__future__/__future__.py diff --git a/__future__/metadata.txt b/python-stdlib/__future__/metadata.txt similarity index 100% rename from __future__/metadata.txt rename to python-stdlib/__future__/metadata.txt diff --git a/python-stdlib/__future__/setup.py b/python-stdlib/__future__/setup.py new file mode 100644 index 000000000..9195f702f --- /dev/null +++ b/python-stdlib/__future__/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-future", + version="0.0.3", + description="Dummy __future__ module for MicroPython", + long_description="This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.", + url="https://github.com/micropython/micropython-lib", + author="micropython-lib Developers", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["__future__"], +) diff --git a/_markupbase/_markupbase.py b/python-stdlib/_markupbase/_markupbase.py similarity index 83% rename from _markupbase/_markupbase.py rename to python-stdlib/_markupbase/_markupbase.py index 2af5f1c23..7e1d91478 100644 --- a/_markupbase/_markupbase.py +++ b/python-stdlib/_markupbase/_markupbase.py @@ -7,15 +7,15 @@ import re -_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9]*\s*').match +_declname_match = re.compile(r"[a-zA-Z][-_.a-zA-Z0-9]*\s*").match _declstringlit_match = re.compile(r'(\'[^\']*\'|"[^"]*")\s*').match -_commentclose = re.compile(r'--\s*>') -_markedsectionclose = re.compile(r']\s*]\s*>') +_commentclose = re.compile(r"--\s*>") +_markedsectionclose = re.compile(r"]\s*]\s*>") # An analysis of the MS-Word extensions is available at # http://www.planetpublish.com/xmlarena/xap/Thursday/WordtoXML.pdf -_msmarkedsectionclose = re.compile(r']\s*>') +_msmarkedsectionclose = re.compile(r"]\s*>") del re @@ -26,12 +26,10 @@ class ParserBase: def __init__(self): if self.__class__ is ParserBase: - raise RuntimeError( - "_markupbase.ParserBase must be subclassed") + raise RuntimeError("_markupbase.ParserBase must be subclassed") def error(self, message): - raise NotImplementedError( - "subclasses of ParserBase must override error()") + raise NotImplementedError("subclasses of ParserBase must override error()") def reset(self): self.lineno = 1 @@ -52,13 +50,13 @@ def updatepos(self, i, j): nlines = rawdata.count("\n", i, j) if nlines: self.lineno = self.lineno + nlines - pos = rawdata.rindex("\n", i, j) # Should not fail - self.offset = j-(pos+1) + pos = rawdata.rindex("\n", i, j) # Should not fail + self.offset = j - (pos + 1) else: - self.offset = self.offset + j-i + self.offset = self.offset + j - i return j - _decl_otherchars = '' + _decl_otherchars = "" # Internal -- parse declaration (for use by subclasses). def parse_declaration(self, i): @@ -75,35 +73,35 @@ def parse_declaration(self, i): rawdata = self.rawdata j = i + 2 assert rawdata[i:j] == "": + if rawdata[j : j + 1] == ">": # the empty comment return j + 1 - if rawdata[j:j+1] in ("-", ""): + if rawdata[j : j + 1] in ("-", ""): # Start of comment followed by buffer boundary, # or just a buffer boundary. return -1 # A simple, practical version could look like: ((name|stringlit) S*) + '>' n = len(rawdata) - if rawdata[j:j+2] == '--': #comment + if rawdata[j : j + 2] == "--": # comment # Locate --.*-- as the body of the comment return self.parse_comment(i) - elif rawdata[j] == '[': #marked section + elif rawdata[j] == "[": # marked section # Locate [statusWord [...arbitrary SGML...]] as the body of the marked section # Where statusWord is one of TEMP, CDATA, IGNORE, INCLUDE, RCDATA # Note that this is extended by Microsoft Office "Save as Web" function # to include [if...] and [endif]. return self.parse_marked_section(i) - else: #all other declaration elements + else: # all other declaration elements decltype, j = self._scan_name(j, i) if j < 0: return j if decltype == "doctype": - self._decl_otherchars = '' + self._decl_otherchars = "" while j < n: c = rawdata[j] if c == ">": # end of declaration syntax - data = rawdata[i+2:j] + data = rawdata[i + 2 : j] if decltype == "doctype": self.handle_decl(data) else: @@ -116,7 +114,7 @@ def parse_declaration(self, i): if c in "\"'": m = _declstringlit_match(rawdata, j) if not m: - return -1 # incomplete + return -1 # incomplete j = m.end() elif c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ": name, j = self._scan_name(j, i) @@ -135,46 +133,45 @@ def parse_declaration(self, i): else: self.error("unexpected '[' char in declaration") else: - self.error( - "unexpected %r char in declaration" % rawdata[j]) + self.error("unexpected %r char in declaration" % rawdata[j]) if j < 0: return j - return -1 # incomplete + return -1 # incomplete # Internal -- parse a marked section # Override this to handle MS-word extension syntax content def parse_marked_section(self, i, report=1): - rawdata= self.rawdata - assert rawdata[i:i+3] == ' ending - match= _markedsectionclose.search(rawdata, i+3) + match = _markedsectionclose.search(rawdata, i + 3) elif sectName in {"if", "else", "endif"}: # look for MS Office ]> ending - match= _msmarkedsectionclose.search(rawdata, i+3) + match = _msmarkedsectionclose.search(rawdata, i + 3) else: - self.error('unknown status keyword %r in marked section' % rawdata[i+3:j]) + self.error("unknown status keyword %r in marked section" % rawdata[i + 3 : j]) if not match: return -1 if report: j = match.start(0) - self.unknown_decl(rawdata[i+3: j]) + self.unknown_decl(rawdata[i + 3 : j]) return match.end(0) # Internal -- parse comment, return length or -1 if not terminated def parse_comment(self, i, report=1): rawdata = self.rawdata - if rawdata[i:i+4] != ' 'type://host/path' @@ -820,6 +950,7 @@ def urlencode(query, doseq=False, safe='', encoding=None, errors=None): # urllib.parse.unquote('abc%20def') -> 'abc def' # quote('abc def') -> 'abc%20def') + def to_bytes(url): """to_bytes(u"URL") --> 'URL'.""" # Most URL schemes require ASCII. If that changes, the conversion @@ -829,87 +960,114 @@ def to_bytes(url): try: url = url.encode("ASCII").decode() except UnicodeError: - raise UnicodeError("URL " + repr(url) + - " contains non-ASCII characters") + raise UnicodeError("URL " + repr(url) + " contains non-ASCII characters") return url + def unwrap(url): """unwrap('') --> 'type://host/path'.""" url = str(url).strip() - if url[:1] == '<' and url[-1:] == '>': + if url[:1] == "<" and url[-1:] == ">": url = url[1:-1].strip() - if url[:4] == 'URL:': url = url[4:].strip() + if url[:4] == "URL:": + url = url[4:].strip() return url + _typeprog = None + + def splittype(url): """splittype('type:opaquestring') --> 'type', 'opaquestring'.""" global _typeprog if _typeprog is None: import re - _typeprog = re.compile('^([^/:]+):') + + _typeprog = re.compile("^([^/:]+):") match = _typeprog.match(url) if match: scheme = match.group(1) - return scheme.lower(), url[len(scheme) + 1:] + return scheme.lower(), url[len(scheme) + 1 :] return None, url + _hostprog = None + + def splithost(url): """splithost('//host[:port]/path') --> 'host[:port]', '/path'.""" global _hostprog if _hostprog is None: import re - _hostprog = re.compile('^//([^/?]*)(.*)$') + + _hostprog = re.compile("^//([^/?]*)(.*)$") match = _hostprog.match(url) if match: host_port = match.group(1) path = match.group(2) - if path and not path.startswith('/'): - path = '/' + path + if path and not path.startswith("/"): + path = "/" + path return host_port, path return None, url + _userprog = None + + def splituser(host): """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.""" global _userprog if _userprog is None: import re - _userprog = re.compile('^(.*)@(.*)$') + + _userprog = re.compile("^(.*)@(.*)$") match = _userprog.match(host) - if match: return match.group(1, 2) + if match: + return match.group(1, 2) return None, host + _passwdprog = None + + def splitpasswd(user): """splitpasswd('user:passwd') -> 'user', 'passwd'.""" global _passwdprog if _passwdprog is None: import re - _passwdprog = re.compile('^([^:]*):(.*)$',re.S) + + _passwdprog = re.compile("^([^:]*):(.*)$", re.S) match = _passwdprog.match(user) - if match: return match.group(1, 2) + if match: + return match.group(1, 2) return user, None + # splittag('/path#tag') --> '/path', 'tag' _portprog = None + + def splitport(host): """splitport('host:port') --> 'host', 'port'.""" global _portprog if _portprog is None: import re - _portprog = re.compile('^(.*):([0-9]+)$') + + _portprog = re.compile("^(.*):([0-9]+)$") match = _portprog.match(host) - if match: return match.group(1, 2) + if match: + return match.group(1, 2) return host, None + _nportprog = None + + def splitnport(host, defport=-1): """Split host and port, returning numeric port. Return given default port if no ':' found; defaults to -1. @@ -918,57 +1076,75 @@ def splitnport(host, defport=-1): global _nportprog if _nportprog is None: import re - _nportprog = re.compile('^(.*):(.*)$') + + _nportprog = re.compile("^(.*):(.*)$") match = _nportprog.match(host) if match: host, port = match.group(1, 2) try: - if not port: raise ValueError("no digits") + if not port: + raise ValueError("no digits") nport = int(port) except ValueError: nport = None return host, nport return host, defport + _queryprog = None + + def splitquery(url): """splitquery('/path?query') --> '/path', 'query'.""" global _queryprog if _queryprog is None: import re - _queryprog = re.compile('^(.*)\?([^?]*)$') + + _queryprog = re.compile("^(.*)\?([^?]*)$") match = _queryprog.match(url) - if match: return match.group(1, 2) + if match: + return match.group(1, 2) return url, None + _tagprog = None + + def splittag(url): """splittag('/path#tag') --> '/path', 'tag'.""" global _tagprog if _tagprog is None: import re - _tagprog = re.compile('^(.*)#([^#]*)$') + + _tagprog = re.compile("^(.*)#([^#]*)$") match = _tagprog.match(url) - if match: return match.group(1, 2) + if match: + return match.group(1, 2) return url, None + def splitattr(url): """splitattr('/path;attr1=value1;attr2=value2;...') -> - '/path', ['attr1=value1', 'attr2=value2', ...].""" - words = url.split(';') + '/path', ['attr1=value1', 'attr2=value2', ...].""" + words = url.split(";") return words[0], words[1:] + _valueprog = None + + def splitvalue(attr): """splitvalue('attr=value') --> 'attr', 'value'.""" global _valueprog if _valueprog is None: import re - _valueprog = re.compile('^([^=]*)=(.*)$') + + _valueprog = re.compile("^([^=]*)=(.*)$") match = _valueprog.match(attr) - if match: return match.group(1, 2) + if match: + return match.group(1, 2) return attr, None diff --git a/uu/metadata.txt b/python-stdlib/uu/metadata.txt similarity index 100% rename from uu/metadata.txt rename to python-stdlib/uu/metadata.txt diff --git a/python-stdlib/uu/setup.py b/python-stdlib/uu/setup.py new file mode 100644 index 000000000..29fe8ebf0 --- /dev/null +++ b/python-stdlib/uu/setup.py @@ -0,0 +1,25 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-uu", + version="0.5.1", + description="CPython uu module ported to MicroPython", + long_description="This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.", + url="https://github.com/micropython/micropython-lib", + author="CPython Developers", + author_email="python-dev@python.org", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="Python", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["uu"], + install_requires=["micropython-binascii", "micropython-os"], +) diff --git a/uu/uu.py b/python-stdlib/uu/uu.py similarity index 75% rename from uu/uu.py rename to python-stdlib/uu/uu.py index d68d29374..03f8b2df1 100644 --- a/uu/uu.py +++ b/python-stdlib/uu/uu.py @@ -36,9 +36,11 @@ __all__ = ["Error", "encode", "decode"] + class Error(Exception): pass + def encode(in_file, out_file, name=None, mode=None): """Uuencode file""" # @@ -46,7 +48,7 @@ def encode(in_file, out_file, name=None, mode=None): # opened_files = [] try: - if in_file == '-': + if in_file == "-": in_file = sys.stdin.buffer elif isinstance(in_file, str): if name is None: @@ -56,32 +58,32 @@ def encode(in_file, out_file, name=None, mode=None): mode = os.stat(in_file).st_mode except AttributeError: pass - in_file = open(in_file, 'rb') + in_file = open(in_file, "rb") opened_files.append(in_file) # # Open out_file if it is a pathname # - if out_file == '-': + if out_file == "-": out_file = sys.stdout.buffer elif isinstance(out_file, str): - out_file = open(out_file, 'wb') + out_file = open(out_file, "wb") opened_files.append(out_file) # # Set defaults for name and mode # if name is None: - name = '-' + name = "-" if mode is None: mode = 0o666 # # Write the data # - out_file.write(('begin %o %s\n' % ((mode & 0o777), name)).encode("ascii")) + out_file.write(("begin %o %s\n" % ((mode & 0o777), name)).encode("ascii")) data = in_file.read(45) while len(data) > 0: out_file.write(binascii.b2a_uu(data)) data = in_file.read(45) - out_file.write(b' \nend\n') + out_file.write(b" \nend\n") finally: for f in opened_files: f.close() @@ -93,10 +95,10 @@ def decode(in_file, out_file=None, mode=None, quiet=False): # Open the input file, if needed. # opened_files = [] - if in_file == '-': + if in_file == "-": in_file = sys.stdin.buffer elif isinstance(in_file, str): - in_file = open(in_file, 'rb') + in_file = open(in_file, "rb") opened_files.append(in_file) try: @@ -106,11 +108,11 @@ def decode(in_file, out_file=None, mode=None, quiet=False): while True: hdr = in_file.readline() if not hdr: - raise Error('No valid begin line found in input file') - if not hdr.startswith(b'begin'): + raise Error("No valid begin line found in input file") + if not hdr.startswith(b"begin"): continue - hdrfields = hdr.split(b' ', 2) - if len(hdrfields) == 3 and hdrfields[0] == b'begin': + hdrfields = hdr.split(b" ", 2) + if len(hdrfields) == 3 and hdrfields[0] == b"begin": try: int(hdrfields[1], 8) break @@ -118,18 +120,18 @@ def decode(in_file, out_file=None, mode=None, quiet=False): pass if out_file is None: # If the filename isn't ASCII, what's up with that?!? - out_file = hdrfields[2].rstrip(b' \t\r\n\f').decode("ascii") + out_file = hdrfields[2].rstrip(b" \t\r\n\f").decode("ascii") if os.path.exists(out_file): - raise Error('Cannot overwrite existing file: %s' % out_file) + raise Error("Cannot overwrite existing file: %s" % out_file) if mode is None: mode = int(hdrfields[1], 8) # # Open the output file # - if out_file == '-': + if out_file == "-": out_file = sys.stdout.buffer elif isinstance(out_file, str): - fp = open(out_file, 'wb') + fp = open(out_file, "wb") try: os.path.chmod(out_file, mode) except AttributeError: @@ -140,34 +142,50 @@ def decode(in_file, out_file=None, mode=None, quiet=False): # Main decoding loop # s = in_file.readline() - while s and s.strip(b' \t\r\n\f') != b'end': + while s and s.strip(b" \t\r\n\f") != b"end": try: data = binascii.a2b_uu(s) except binascii.Error as v: # Workaround for broken uuencoders by /Fredrik Lundh - nbytes = (((s[0]-32) & 63) * 4 + 5) // 3 + nbytes = (((s[0] - 32) & 63) * 4 + 5) // 3 data = binascii.a2b_uu(s[:nbytes]) if not quiet: sys.stderr.write("Warning: %s\n" % v) out_file.write(data) s = in_file.readline() if not s: - raise Error('Truncated input file') + raise Error("Truncated input file") finally: for f in opened_files: f.close() + def test(): """uuencode/uudecode main program""" import optparse - parser = optparse.OptionParser(usage='usage: %prog [-d] [-t] [input [output]]') - parser.add_option('-d', '--decode', dest='decode', help='Decode (instead of encode)?', default=False, action='store_true') - parser.add_option('-t', '--text', dest='text', help='data is text, encoded format unix-compatible text?', default=False, action='store_true') + + parser = optparse.OptionParser(usage="usage: %prog [-d] [-t] [input [output]]") + parser.add_option( + "-d", + "--decode", + dest="decode", + help="Decode (instead of encode)?", + default=False, + action="store_true", + ) + parser.add_option( + "-t", + "--text", + dest="text", + help="data is text, encoded format unix-compatible text?", + default=False, + action="store_true", + ) (options, args) = parser.parse_args() if len(args) > 2: - parser.error('incorrect number of arguments') + parser.error("incorrect number of arguments") sys.exit(1) # Use the binary streams underlying stdin/stdout @@ -181,19 +199,20 @@ def test(): if options.decode: if options.text: if isinstance(output, str): - output = open(output, 'wb') + output = open(output, "wb") else: - print(sys.argv[0], ': cannot do -t to stdout') + print(sys.argv[0], ": cannot do -t to stdout") sys.exit(1) decode(input, output) else: if options.text: if isinstance(input, str): - input = open(input, 'rb') + input = open(input, "rb") else: - print(sys.argv[0], ': cannot do -t from stdin') + print(sys.argv[0], ": cannot do -t from stdin") sys.exit(1) encode(input, output) -if __name__ == '__main__': + +if __name__ == "__main__": test() diff --git a/python-stdlib/warnings/example_warn.py b/python-stdlib/warnings/example_warn.py new file mode 100644 index 000000000..cba2f1065 --- /dev/null +++ b/python-stdlib/warnings/example_warn.py @@ -0,0 +1,4 @@ +import warnings + +warnings.warn("block_size of %d seems too small; using our " "default of %d.", RuntimeError, 2) +# RuntimeWarning, 2) diff --git a/warnings/metadata.txt b/python-stdlib/warnings/metadata.txt similarity index 100% rename from warnings/metadata.txt rename to python-stdlib/warnings/metadata.txt diff --git a/python-stdlib/warnings/setup.py b/python-stdlib/warnings/setup.py new file mode 100644 index 000000000..c93512ad5 --- /dev/null +++ b/python-stdlib/warnings/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-warnings", + version="0.1.1", + description="warnings module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="micropython-lib Developers", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["warnings"], +) diff --git a/warnings/warnings.py b/python-stdlib/warnings/warnings.py similarity index 100% rename from warnings/warnings.py rename to python-stdlib/warnings/warnings.py diff --git a/queue/metadata.txt b/queue/metadata.txt deleted file mode 100644 index fda992a9c..000000000 --- a/queue/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.2 diff --git a/queue/queue.py b/queue/queue.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/queue/setup.py b/queue/setup.py deleted file mode 100644 index c5d58d40b..000000000 --- a/queue/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-queue', - version='0.0.2', - description='Dummy queue module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['queue']) diff --git a/quopri/setup.py b/quopri/setup.py deleted file mode 100644 index 0e0caf074..000000000 --- a/quopri/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-quopri', - version='0.5.1', - description='CPython quopri module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['quopri']) diff --git a/random/setup.py b/random/setup.py deleted file mode 100644 index 781597962..000000000 --- a/random/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-random', - version='0.2', - description='Dummy random module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['random']) diff --git a/re-pcre/setup.py b/re-pcre/setup.py deleted file mode 100644 index 9c9cc0f2a..000000000 --- a/re-pcre/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-re-pcre', - version='0.2.5', - description='re-pcre module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['re'], - install_requires=['micropython-ffilib']) diff --git a/readline/metadata.txt b/readline/metadata.txt deleted file mode 100644 index 976088c8a..000000000 --- a/readline/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.0 diff --git a/readline/readline.py b/readline/readline.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/readline/setup.py b/readline/setup.py deleted file mode 100644 index 1d6fef35c..000000000 --- a/readline/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-readline', - version='0.0.0', - description='Dummy readline module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['readline']) diff --git a/reprlib/metadata.txt b/reprlib/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/reprlib/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/reprlib/reprlib.py b/reprlib/reprlib.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/reprlib/setup.py b/reprlib/setup.py deleted file mode 100644 index 916f587c9..000000000 --- a/reprlib/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-reprlib', - version='0.0.1', - description='Dummy reprlib module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['reprlib']) diff --git a/runpy/metadata.txt b/runpy/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/runpy/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/runpy/runpy.py b/runpy/runpy.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/runpy/setup.py b/runpy/setup.py deleted file mode 100644 index 75d4d2062..000000000 --- a/runpy/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-runpy', - version='0.0.1', - description='Dummy runpy module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['runpy']) diff --git a/sched/metadata.txt b/sched/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/sched/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/sched/sched.py b/sched/sched.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/sched/setup.py b/sched/setup.py deleted file mode 100644 index f2c314c58..000000000 --- a/sched/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-sched', - version='0.0.1', - description='Dummy sched module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['sched']) diff --git a/sdist_upip.py b/sdist_upip.py deleted file mode 100644 index 290b8c973..000000000 --- a/sdist_upip.py +++ /dev/null @@ -1,141 +0,0 @@ -# -# This module overrides distutils (also compatible with setuptools) "sdist" -# command to perform pre- and post-processing as required for MicroPython's -# upip package manager. -# -# Preprocessing steps: -# * Creation of Python resource module (R.py) from each top-level package's -# resources. -# Postprocessing steps: -# * Removing metadata files not used by upip (this includes setup.py) -# * Recompressing gzip archive with 4K dictionary size so it can be -# installed even on low-heap targets. -# -import sys -import os -import zlib -from subprocess import Popen, PIPE -import glob -import tarfile -import re -import io - -from distutils.filelist import FileList -from setuptools.command.sdist import sdist as _sdist - - -def gzip_4k(inf, fname): - comp = zlib.compressobj(level=9, wbits=16 + 12) - with open(fname + ".out", "wb") as outf: - while 1: - data = inf.read(1024) - if not data: - break - outf.write(comp.compress(data)) - outf.write(comp.flush()) - os.rename(fname, fname + ".orig") - os.rename(fname + ".out", fname) - - -FILTERS = [ - # include, exclude, repeat - (r".+\.egg-info/(PKG-INFO|requires\.txt)", r"setup.py$"), - (r".+\.py$", r"[^/]+$"), - (None, r".+\.egg-info/.+"), -] - - -outbuf = io.BytesIO() - -def filter_tar(name): - fin = tarfile.open(name, "r:gz") - fout = tarfile.open(fileobj=outbuf, mode="w") - for info in fin: -# print(info) - if not "/" in info.name: - continue - fname = info.name.split("/", 1)[1] - include = None - - for inc_re, exc_re in FILTERS: - if include is None and inc_re: - if re.match(inc_re, fname): - include = True - - if include is None and exc_re: - if re.match(exc_re, fname): - include = False - - if include is None: - include = True - - if include: - print("including:", fname) - else: - print("excluding:", fname) - continue - - farch = fin.extractfile(info) - fout.addfile(info, farch) - fout.close() - fin.close() - - -def make_resource_module(manifest_files): - resources = [] - # Any non-python file included in manifest is resource - for fname in manifest_files: - ext = fname.rsplit(".", 1)[1] - if ext != "py": - resources.append(fname) - - if resources: - print("creating resource module R.py") - resources.sort() - last_pkg = None - r_file = None - for fname in resources: - try: - pkg, res_name = fname.split("/", 1) - except ValueError: - print("not treating %s as a resource" % fname) - continue - if last_pkg != pkg: - last_pkg = pkg - if r_file: - r_file.write("}\n") - r_file.close() - r_file = open(pkg + "/R.py", "w") - r_file.write("R = {\n") - - with open(fname, "rb") as f: - r_file.write("%r: %r,\n" % (res_name, f.read())) - - if r_file: - r_file.write("}\n") - r_file.close() - - -class sdist(_sdist): - - def run(self): - self.filelist = FileList() - self.get_file_list() - make_resource_module(self.filelist.files) - - r = super().run() - - assert len(self.archive_files) == 1 - print("filtering files and recompressing with 4K dictionary") - filter_tar(self.archive_files[0]) - outbuf.seek(0) - gzip_4k(outbuf, self.archive_files[0]) - - return r - - -# For testing only -if __name__ == "__main__": - filter_tar(sys.argv[1]) - outbuf.seek(0) - gzip_4k(outbuf, sys.argv[1]) diff --git a/select/setup.py b/select/setup.py deleted file mode 100644 index fa4a81f77..000000000 --- a/select/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-select', - version='0.3', - description='select module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['select'], - install_requires=['micropython-os', 'micropython-ffilib']) diff --git a/selectors/metadata.txt b/selectors/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/selectors/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/selectors/selectors.py b/selectors/selectors.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/selectors/setup.py b/selectors/setup.py deleted file mode 100644 index 685f08b53..000000000 --- a/selectors/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-selectors', - version='0.0.1', - description='Dummy selectors module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['selectors']) diff --git a/shelve/metadata.txt b/shelve/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/shelve/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/shelve/setup.py b/shelve/setup.py deleted file mode 100644 index 0b5cfb73c..000000000 --- a/shelve/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-shelve', - version='0.0.1', - description='Dummy shelve module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['shelve']) diff --git a/shelve/shelve.py b/shelve/shelve.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/shlex/metadata.txt b/shlex/metadata.txt deleted file mode 100644 index fda992a9c..000000000 --- a/shlex/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.2 diff --git a/shlex/setup.py b/shlex/setup.py deleted file mode 100644 index f4d15777a..000000000 --- a/shlex/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-shlex', - version='0.0.2', - description='Dummy shlex module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['shlex']) diff --git a/shlex/shlex.py b/shlex/shlex.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/shutil/setup.py b/shutil/setup.py deleted file mode 100644 index ab7f7d634..000000000 --- a/shutil/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-shutil', - version='0.0.3', - description='shutil module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['shutil']) diff --git a/signal/setup.py b/signal/setup.py deleted file mode 100644 index 1feae1d22..000000000 --- a/signal/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-signal', - version='0.3.2', - description='signal module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['signal'], - install_requires=['micropython-ffilib']) diff --git a/smtplib/metadata.txt b/smtplib/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/smtplib/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/smtplib/setup.py b/smtplib/setup.py deleted file mode 100644 index 2b501865e..000000000 --- a/smtplib/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-smtplib', - version='0.0.1', - description='Dummy smtplib module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['smtplib']) diff --git a/smtplib/smtplib.py b/smtplib/smtplib.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/socket/setup.py b/socket/setup.py deleted file mode 100644 index dc05feb44..000000000 --- a/socket/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-socket', - version='0.5.2', - description='socket module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['socket']) diff --git a/socketserver/metadata.txt b/socketserver/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/socketserver/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/socketserver/setup.py b/socketserver/setup.py deleted file mode 100644 index 84e9a0411..000000000 --- a/socketserver/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-socketserver', - version='0.0.1', - description='Dummy socketserver module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['socketserver']) diff --git a/socketserver/socketserver.py b/socketserver/socketserver.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/sqlite3/setup.py b/sqlite3/setup.py deleted file mode 100644 index 3e78a414c..000000000 --- a/sqlite3/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-sqlite3', - version='0.2.4', - description='sqlite3 module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['sqlite3'], - install_requires=['micropython-ffilib']) diff --git a/ssl/setup.py b/ssl/setup.py deleted file mode 100644 index 6987286a2..000000000 --- a/ssl/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-ssl', - version='0.1', - description='Dummy ssl module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['ssl']) diff --git a/stat/setup.py b/stat/setup.py deleted file mode 100644 index e83d07233..000000000 --- a/stat/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-stat', - version='0.5.1', - description='CPython stat module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['stat']) diff --git a/statistics/metadata.txt b/statistics/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/statistics/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/statistics/setup.py b/statistics/setup.py deleted file mode 100644 index dd716f0c8..000000000 --- a/statistics/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-statistics', - version='0.0.1', - description='Dummy statistics module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['statistics']) diff --git a/statistics/statistics.py b/statistics/statistics.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/string/setup.py b/string/setup.py deleted file mode 100644 index 62031391b..000000000 --- a/string/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-string', - version='0.1.1', - description='string module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['string']) diff --git a/stringprep/metadata.txt b/stringprep/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/stringprep/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/stringprep/setup.py b/stringprep/setup.py deleted file mode 100644 index 37eeb7c59..000000000 --- a/stringprep/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-stringprep', - version='0.0.1', - description='Dummy stringprep module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['stringprep']) diff --git a/stringprep/stringprep.py b/stringprep/stringprep.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/struct/setup.py b/struct/setup.py deleted file mode 100644 index 64472e7bf..000000000 --- a/struct/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-struct', - version='0.1.1', - description='struct module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['struct']) diff --git a/subprocess/metadata.txt b/subprocess/metadata.txt deleted file mode 100644 index fda992a9c..000000000 --- a/subprocess/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.2 diff --git a/subprocess/setup.py b/subprocess/setup.py deleted file mode 100644 index b527ac827..000000000 --- a/subprocess/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-subprocess', - version='0.0.2', - description='Dummy subprocess module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['subprocess']) diff --git a/subprocess/subprocess.py b/subprocess/subprocess.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/sys/metadata.txt b/sys/metadata.txt deleted file mode 100644 index 976088c8a..000000000 --- a/sys/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.0 diff --git a/sys/setup.py b/sys/setup.py deleted file mode 100644 index 52d750eba..000000000 --- a/sys/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-sys', - version='0.0.0', - description='Dummy sys module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['sys']) diff --git a/sys/sys.py b/sys/sys.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/tarfile/metadata.txt b/tarfile/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/tarfile/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/tarfile/setup.py b/tarfile/setup.py deleted file mode 100644 index ae591e990..000000000 --- a/tarfile/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-tarfile', - version='0.0.1', - description='Dummy tarfile module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['tarfile']) diff --git a/tarfile/tarfile.py b/tarfile/tarfile.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/telnetlib/metadata.txt b/telnetlib/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/telnetlib/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/telnetlib/setup.py b/telnetlib/setup.py deleted file mode 100644 index dc0cdb5c0..000000000 --- a/telnetlib/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-telnetlib', - version='0.0.1', - description='Dummy telnetlib module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['telnetlib']) diff --git a/telnetlib/telnetlib.py b/telnetlib/telnetlib.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/tempfile/metadata.txt b/tempfile/metadata.txt deleted file mode 100644 index fda992a9c..000000000 --- a/tempfile/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.2 diff --git a/tempfile/setup.py b/tempfile/setup.py deleted file mode 100644 index e237e9d1a..000000000 --- a/tempfile/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-tempfile', - version='0.0.2', - description='Dummy tempfile module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['tempfile']) diff --git a/tempfile/tempfile.py b/tempfile/tempfile.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/test.pystone/setup.py b/test.pystone/setup.py deleted file mode 100644 index bb3533226..000000000 --- a/test.pystone/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-test.pystone', - version='1.0.1', - description='CPython test.pystone module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['test']) diff --git a/test.support/setup.py b/test.support/setup.py deleted file mode 100644 index e7751869d..000000000 --- a/test.support/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-test.support', - version='0.1.3', - description='test.support module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['test']) diff --git a/test/test_pep380.py b/test/test_pep380.py deleted file mode 100644 index 11d659496..000000000 --- a/test/test_pep380.py +++ /dev/null @@ -1,1030 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -Test suite for PEP 380 implementation - -adapted from original tests written by Greg Ewing -see -""" - -import unittest -import io -import sys -import inspect -#import parser - -from test.support import captured_stderr, disable_gc, gc_collect - -class TestPEP380Operation(unittest.TestCase): - """ - Test semantics. - """ - - def test_delegation_of_initial_next_to_subgenerator(self): - """ - Test delegation of initial next() call to subgenerator - """ - trace = [] - def g1(): - trace.append("Starting g1") - yield from g2() - trace.append("Finishing g1") - def g2(): - trace.append("Starting g2") - yield 42 - trace.append("Finishing g2") - for x in g1(): - trace.append("Yielded %s" % (x,)) - self.assertEqual(trace,[ - "Starting g1", - "Starting g2", - "Yielded 42", - "Finishing g2", - "Finishing g1", - ]) - - def test_raising_exception_in_initial_next_call(self): - """ - Test raising exception in initial next() call - """ - trace = [] - def g1(): - try: - trace.append("Starting g1") - yield from g2() - finally: - trace.append("Finishing g1") - def g2(): - try: - trace.append("Starting g2") - raise ValueError("spanish inquisition occurred") - finally: - trace.append("Finishing g2") - try: - for x in g1(): - trace.append("Yielded %s" % (x,)) - except ValueError as e: - self.assertEqual(e.args[0], "spanish inquisition occurred") - else: - self.fail("subgenerator failed to raise ValueError") - self.assertEqual(trace,[ - "Starting g1", - "Starting g2", - "Finishing g2", - "Finishing g1", - ]) - - def test_delegation_of_next_call_to_subgenerator(self): - """ - Test delegation of next() call to subgenerator - """ - trace = [] - def g1(): - trace.append("Starting g1") - yield "g1 ham" - yield from g2() - yield "g1 eggs" - trace.append("Finishing g1") - def g2(): - trace.append("Starting g2") - yield "g2 spam" - yield "g2 more spam" - trace.append("Finishing g2") - for x in g1(): - trace.append("Yielded %s" % (x,)) - self.assertEqual(trace,[ - "Starting g1", - "Yielded g1 ham", - "Starting g2", - "Yielded g2 spam", - "Yielded g2 more spam", - "Finishing g2", - "Yielded g1 eggs", - "Finishing g1", - ]) - - def test_raising_exception_in_delegated_next_call(self): - """ - Test raising exception in delegated next() call - """ - trace = [] - def g1(): - try: - trace.append("Starting g1") - yield "g1 ham" - yield from g2() - yield "g1 eggs" - finally: - trace.append("Finishing g1") - def g2(): - try: - trace.append("Starting g2") - yield "g2 spam" - raise ValueError("hovercraft is full of eels") - yield "g2 more spam" - finally: - trace.append("Finishing g2") - try: - for x in g1(): - trace.append("Yielded %s" % (x,)) - except ValueError as e: - self.assertEqual(e.args[0], "hovercraft is full of eels") - else: - self.fail("subgenerator failed to raise ValueError") - self.assertEqual(trace,[ - "Starting g1", - "Yielded g1 ham", - "Starting g2", - "Yielded g2 spam", - "Finishing g2", - "Finishing g1", - ]) - - def test_delegation_of_send(self): - """ - Test delegation of send() - """ - trace = [] - def g1(): - trace.append("Starting g1") - x = yield "g1 ham" - trace.append("g1 received %s" % (x,)) - yield from g2() - x = yield "g1 eggs" - trace.append("g1 received %s" % (x,)) - trace.append("Finishing g1") - def g2(): - trace.append("Starting g2") - x = yield "g2 spam" - trace.append("g2 received %s" % (x,)) - x = yield "g2 more spam" - trace.append("g2 received %s" % (x,)) - trace.append("Finishing g2") - g = g1() - y = next(g) - x = 1 - try: - while 1: - y = g.send(x) - trace.append("Yielded %s" % (y,)) - x += 1 - except StopIteration: - pass - self.assertEqual(trace,[ - "Starting g1", - "g1 received 1", - "Starting g2", - "Yielded g2 spam", - "g2 received 2", - "Yielded g2 more spam", - "g2 received 3", - "Finishing g2", - "Yielded g1 eggs", - "g1 received 4", - "Finishing g1", - ]) - - def test_handling_exception_while_delegating_send(self): - """ - Test handling exception while delegating 'send' - """ - trace = [] - def g1(): - trace.append("Starting g1") - x = yield "g1 ham" - trace.append("g1 received %s" % (x,)) - yield from g2() - x = yield "g1 eggs" - trace.append("g1 received %s" % (x,)) - trace.append("Finishing g1") - def g2(): - trace.append("Starting g2") - x = yield "g2 spam" - trace.append("g2 received %s" % (x,)) - raise ValueError("hovercraft is full of eels") - x = yield "g2 more spam" - trace.append("g2 received %s" % (x,)) - trace.append("Finishing g2") - def run(): - g = g1() - y = next(g) - x = 1 - try: - while 1: - y = g.send(x) - trace.append("Yielded %s" % (y,)) - x += 1 - except StopIteration: - trace.append("StopIteration") - self.assertRaises(ValueError,run) - self.assertEqual(trace,[ - "Starting g1", - "g1 received 1", - "Starting g2", - "Yielded g2 spam", - "g2 received 2", - ]) - - def test_delegating_close(self): - """ - Test delegating 'close' - """ - trace = [] - def g1(): - try: - trace.append("Starting g1") - yield "g1 ham" - yield from g2() - yield "g1 eggs" - finally: - trace.append("Finishing g1") - def g2(): - try: - trace.append("Starting g2") - yield "g2 spam" - yield "g2 more spam" - finally: - trace.append("Finishing g2") - g = g1() - for i in range(2): - x = next(g) - trace.append("Yielded %s" % (x,)) - g.close() - self.assertEqual(trace,[ - "Starting g1", - "Yielded g1 ham", - "Starting g2", - "Yielded g2 spam", - "Finishing g2", - "Finishing g1" - ]) - - def test_handing_exception_while_delegating_close(self): - """ - Test handling exception while delegating 'close' - """ - trace = [] - def g1(): - try: - trace.append("Starting g1") - yield "g1 ham" - yield from g2() - yield "g1 eggs" - finally: - trace.append("Finishing g1") - def g2(): - try: - trace.append("Starting g2") - yield "g2 spam" - yield "g2 more spam" - finally: - trace.append("Finishing g2") - raise ValueError("nybbles have exploded with delight") - try: - g = g1() - for i in range(2): - x = next(g) - trace.append("Yielded %s" % (x,)) - g.close() - except ValueError as e: - self.assertEqual(e.args[0], "nybbles have exploded with delight") -# MicroPython doesn't support nested exceptions -# self.assertIsInstance(e.__context__, GeneratorExit) - else: - self.fail("subgenerator failed to raise ValueError") - self.assertEqual(trace,[ - "Starting g1", - "Yielded g1 ham", - "Starting g2", - "Yielded g2 spam", - "Finishing g2", - "Finishing g1", - ]) - - def test_delegating_throw(self): - """ - Test delegating 'throw' - """ - trace = [] - def g1(): - try: - trace.append("Starting g1") - yield "g1 ham" - yield from g2() - yield "g1 eggs" - finally: - trace.append("Finishing g1") - def g2(): - try: - trace.append("Starting g2") - yield "g2 spam" - yield "g2 more spam" - finally: - trace.append("Finishing g2") - try: - g = g1() - for i in range(2): - x = next(g) - trace.append("Yielded %s" % (x,)) - e = ValueError("tomato ejected") - g.throw(e) - except ValueError as e: - self.assertEqual(e.args[0], "tomato ejected") - else: - self.fail("subgenerator failed to raise ValueError") - self.assertEqual(trace,[ - "Starting g1", - "Yielded g1 ham", - "Starting g2", - "Yielded g2 spam", - "Finishing g2", - "Finishing g1", - ]) - - def test_value_attribute_of_StopIteration_exception(self): - """ - Test 'value' attribute of StopIteration exception - """ - trace = [] - def pex(e): - trace.append("%s: %s" % (e.__class__.__name__, e)) - trace.append("value = %s" % (e.value,)) - e = StopIteration() - pex(e) - e = StopIteration("spam") - pex(e) -# MicroPython doesn't support assignment to .value -# e.value = "eggs" -# pex(e) - self.assertEqual(trace,[ - "StopIteration: ", - "value = None", - "StopIteration: spam", - "value = spam", -# "StopIteration: spam", -# "value = eggs", - ]) - - - def test_exception_value_crash(self): - # There used to be a refcount error when the return value - # stored in the StopIteration has a refcount of 1. - def g1(): - yield from g2() - def g2(): - yield "g2" - return [42] - self.assertEqual(list(g1()), ["g2"]) - - - def test_generator_return_value(self): - """ - Test generator return value - """ - trace = [] - def g1(): - trace.append("Starting g1") - yield "g1 ham" - ret = yield from g2() - trace.append("g2 returned %s" % (ret,)) - ret = yield from g2(42) - trace.append("g2 returned %s" % (ret,)) - yield "g1 eggs" - trace.append("Finishing g1") - def g2(v = None): - trace.append("Starting g2") - yield "g2 spam" - yield "g2 more spam" - trace.append("Finishing g2") - if v: - return v - for x in g1(): - trace.append("Yielded %s" % (x,)) - self.assertEqual(trace,[ - "Starting g1", - "Yielded g1 ham", - "Starting g2", - "Yielded g2 spam", - "Yielded g2 more spam", - "Finishing g2", - "g2 returned None", - "Starting g2", - "Yielded g2 spam", - "Yielded g2 more spam", - "Finishing g2", - "g2 returned 42", - "Yielded g1 eggs", - "Finishing g1", - ]) - - def test_delegation_of_next_to_non_generator(self): - """ - Test delegation of next() to non-generator - """ - trace = [] - def g(): - yield from range(3) - for x in g(): - trace.append("Yielded %s" % (x,)) - self.assertEqual(trace,[ - "Yielded 0", - "Yielded 1", - "Yielded 2", - ]) - - - def test_conversion_of_sendNone_to_next(self): - """ - Test conversion of send(None) to next() - """ - trace = [] - def g(): - yield from range(3) - gi = g() - for x in range(3): - y = gi.send(None) - trace.append("Yielded: %s" % (y,)) - self.assertEqual(trace,[ - "Yielded: 0", - "Yielded: 1", - "Yielded: 2", - ]) - - def test_delegation_of_close_to_non_generator(self): - """ - Test delegation of close() to non-generator - """ - trace = [] - def g(): - try: - trace.append("starting g") - yield from range(3) - trace.append("g should not be here") - finally: - trace.append("finishing g") - gi = g() - next(gi) - with captured_stderr() as output: - gi.close() - self.assertEqual(output.getvalue(), '') - self.assertEqual(trace,[ - "starting g", - "finishing g", - ]) - - def test_delegating_throw_to_non_generator(self): - """ - Test delegating 'throw' to non-generator - """ - trace = [] - def g(): - try: - trace.append("Starting g") - yield from range(10) - finally: - trace.append("Finishing g") - try: - gi = g() - for i in range(5): - x = next(gi) - trace.append("Yielded %s" % (x,)) - e = ValueError("tomato ejected") - gi.throw(e) - except ValueError as e: - self.assertEqual(e.args[0],"tomato ejected") - else: - self.fail("subgenerator failed to raise ValueError") - self.assertEqual(trace,[ - "Starting g", - "Yielded 0", - "Yielded 1", - "Yielded 2", - "Yielded 3", - "Yielded 4", - "Finishing g", - ]) - - def test_attempting_to_send_to_non_generator(self): - """ - Test attempting to send to non-generator - """ - trace = [] - def g(): - try: - trace.append("starting g") - yield from range(3) - trace.append("g should not be here") - finally: - trace.append("finishing g") - try: - gi = g() - next(gi) - for x in range(3): - y = gi.send(42) - trace.append("Should not have yielded: %s" % (y,)) - except AttributeError as e: - self.assertIn("send", e.args[0]) - else: - self.fail("was able to send into non-generator") - self.assertEqual(trace,[ - "starting g", - "finishing g", - ]) - - def test_broken_getattr_handling(self): - """ - Test subiterator with a broken getattr implementation - """ - class Broken: - def __iter__(self): - return self - def __next__(self): - return 1 - def __getattr__(self, attr): - 1/0 - - def g(): - yield from Broken() - - with self.assertRaises(ZeroDivisionError): - gi = g() - self.assertEqual(next(gi), 1) - gi.send(1) - - with self.assertRaises(ZeroDivisionError): - gi = g() - self.assertEqual(next(gi), 1) - gi.throw(AttributeError) - -# In MicroPython, exceptions is .close() are not ignored/printed to sys.stderr, -# but propagated as usual. -# with captured_stderr() as output: -# gi = g() -# self.assertEqual(next(gi), 1) -# gi.close() -# self.assertIn('ZeroDivisionError', output.getvalue()) - - def test_exception_in_initial_next_call(self): - """ - Test exception in initial next() call - """ - trace = [] - def g1(): - trace.append("g1 about to yield from g2") - yield from g2() - trace.append("g1 should not be here") - def g2(): - yield 1/0 - def run(): - gi = g1() - next(gi) - self.assertRaises(ZeroDivisionError,run) - self.assertEqual(trace,[ - "g1 about to yield from g2" - ]) - - @unittest.skip("MicroPython doesn't check for already active generator when resuming it") - def test_attempted_yield_from_loop(self): - """ - Test attempted yield-from loop - """ - trace = [] - def g1(): - trace.append("g1: starting") - yield "y1" - trace.append("g1: about to yield from g2") - yield from g2() - trace.append("g1 should not be here") - - def g2(): - trace.append("g2: starting") - yield "y2" - trace.append("g2: about to yield from g1") - yield from gi - trace.append("g2 should not be here") - try: - gi = g1() - for y in gi: - trace.append("Yielded: %s" % (y,)) - except ValueError as e: - self.assertEqual(e.args[0],"generator already executing") - else: - self.fail("subgenerator didn't raise ValueError") - self.assertEqual(trace,[ - "g1: starting", - "Yielded: y1", - "g1: about to yield from g2", - "g2: starting", - "Yielded: y2", - "g2: about to yield from g1", - ]) - - def test_returning_value_from_delegated_throw(self): - """ - Test returning value from delegated 'throw' - """ - trace = [] - def g1(): - try: - trace.append("Starting g1") - yield "g1 ham" - yield from g2() - yield "g1 eggs" - finally: - trace.append("Finishing g1") - def g2(): - try: - trace.append("Starting g2") - yield "g2 spam" - yield "g2 more spam" - except LunchError: - trace.append("Caught LunchError in g2") - yield "g2 lunch saved" - yield "g2 yet more spam" - class LunchError(Exception): - pass - g = g1() - for i in range(2): - x = next(g) - trace.append("Yielded %s" % (x,)) - e = LunchError("tomato ejected") - g.throw(e) - for x in g: - trace.append("Yielded %s" % (x,)) - self.assertEqual(trace,[ - "Starting g1", - "Yielded g1 ham", - "Starting g2", - "Yielded g2 spam", - "Caught LunchError in g2", - "Yielded g2 yet more spam", - "Yielded g1 eggs", - "Finishing g1", - ]) - - def test_next_and_return_with_value(self): - """ - Test next and return with value - """ - trace = [] - def f(r): - gi = g(r) - next(gi) - try: - trace.append("f resuming g") - next(gi) - trace.append("f SHOULD NOT BE HERE") - except StopIteration as e: - trace.append("f caught %s" % (repr(e),)) - def g(r): - trace.append("g starting") - yield - trace.append("g returning %s" % (r,)) - return r - f(None) - f(42) - self.assertEqual(trace,[ - "g starting", - "f resuming g", - "g returning None", - "f caught StopIteration()", - "g starting", - "f resuming g", - "g returning 42", - "f caught StopIteration(42,)", - ]) - - def test_send_and_return_with_value(self): - """ - Test send and return with value - """ - trace = [] - def f(r): - gi = g(r) - next(gi) - try: - trace.append("f sending spam to g") - gi.send("spam") - trace.append("f SHOULD NOT BE HERE") - except StopIteration as e: - trace.append("f caught %r" % (e,)) - def g(r): - trace.append("g starting") - x = yield - trace.append("g received %s" % (x,)) - trace.append("g returning %s" % (r,)) - return r - f(None) - f(42) - self.assertEqual(trace,[ - "g starting", - "f sending spam to g", - "g received spam", - "g returning None", - "f caught StopIteration()", - "g starting", - "f sending spam to g", - "g received spam", - "g returning 42", - "f caught StopIteration(42,)", - ]) - - def test_catching_exception_from_subgen_and_returning(self): - """ - Test catching an exception thrown into a - subgenerator and returning a value - """ - trace = [] - def inner(): - try: - yield 1 - except ValueError: - trace.append("inner caught ValueError") - return 2 - - def outer(): - v = yield from inner() - trace.append("inner returned %r to outer" % v) - yield v - g = outer() - trace.append(next(g)) - trace.append(g.throw(ValueError)) - self.assertEqual(trace,[ - 1, - "inner caught ValueError", - "inner returned 2 to outer", - 2, - ]) - - def test_throwing_GeneratorExit_into_subgen_that_returns(self): - """ - Test throwing GeneratorExit into a subgenerator that - catches it and returns normally. - """ - trace = [] - def f(): - try: - trace.append("Enter f") - yield - trace.append("Exit f") - except GeneratorExit: - return - def g(): - trace.append("Enter g") - yield from f() - trace.append("Exit g") - try: - gi = g() - next(gi) - gi.throw(GeneratorExit) - except GeneratorExit: - pass - else: - self.fail("subgenerator failed to raise GeneratorExit") - self.assertEqual(trace,[ - "Enter g", - "Enter f", - ]) - - def test_throwing_GeneratorExit_into_subgenerator_that_yields(self): - """ - Test throwing GeneratorExit into a subgenerator that - catches it and yields. - """ - trace = [] - def f(): - try: - trace.append("Enter f") - yield - trace.append("Exit f") - except GeneratorExit: - yield - def g(): - trace.append("Enter g") - yield from f() - trace.append("Exit g") - try: - gi = g() - next(gi) - gi.throw(GeneratorExit) - except RuntimeError as e: - self.assertEqual(e.args[0], "generator ignored GeneratorExit") - else: - self.fail("subgenerator failed to raise GeneratorExit") - self.assertEqual(trace,[ - "Enter g", - "Enter f", - ]) - - def test_throwing_GeneratorExit_into_subgen_that_raises(self): - """ - Test throwing GeneratorExit into a subgenerator that - catches it and raises a different exception. - """ - trace = [] - def f(): - try: - trace.append("Enter f") - yield - trace.append("Exit f") - except GeneratorExit: - raise ValueError("Vorpal bunny encountered") - def g(): - trace.append("Enter g") - yield from f() - trace.append("Exit g") - try: - gi = g() - next(gi) - gi.throw(GeneratorExit) - except ValueError as e: - self.assertEqual(e.args[0], "Vorpal bunny encountered") -# self.assertIsInstance(e.__context__, GeneratorExit) - else: - self.fail("subgenerator failed to raise ValueError") - self.assertEqual(trace,[ - "Enter g", - "Enter f", - ]) - - def test_yield_from_empty(self): - def g(): - yield from () - self.assertRaises(StopIteration, next, g()) - - @unittest.skip("MicroPython doesn't check for already active generator when resuming it") - def test_delegating_generators_claim_to_be_running(self): - # Check with basic iteration - def one(): - yield 0 - yield from two() - yield 3 - def two(): - yield 1 - try: - yield from g1 - except ValueError: - pass - yield 2 - g1 = one() - self.assertEqual(list(g1), [0, 1, 2, 3]) - # Check with send - g1 = one() - res = [next(g1)] - try: - while True: - res.append(g1.send(42)) - except StopIteration: - pass - self.assertEqual(res, [0, 1, 2, 3]) - # Check with throw - class MyErr(Exception): - pass - def one(): - try: - yield 0 - except MyErr: - pass - yield from two() - try: - yield 3 - except MyErr: - pass - def two(): - try: - yield 1 - except MyErr: - pass - try: - yield from g1 - except ValueError: - pass - try: - yield 2 - except MyErr: - pass - g1 = one() - res = [next(g1)] - try: - while True: - res.append(g1.throw(MyErr)) - except StopIteration: - pass - # Check with close - class MyIt(object): - def __iter__(self): - return self - def __next__(self): - return 42 - def close(self_): - self.assertTrue(g1.gi_running) - self.assertRaises(ValueError, next, g1) - def one(): - yield from MyIt() - g1 = one() - next(g1) - g1.close() - - @unittest.skip("MicroPython doesn't support inspect.stack()") - def test_delegator_is_visible_to_debugger(self): - def call_stack(): - return [f[3] for f in inspect.stack()] - - def gen(): - yield call_stack() - yield call_stack() - yield call_stack() - - def spam(g): - yield from g - - def eggs(g): - yield from g - - for stack in spam(gen()): - self.assertTrue('spam' in stack) - - for stack in spam(eggs(gen())): - self.assertTrue('spam' in stack and 'eggs' in stack) - - def test_custom_iterator_return(self): - # See issue #15568 - class MyIter: - def __iter__(self): - return self - def __next__(self): - raise StopIteration(42) - def gen(): - nonlocal ret - ret = yield from MyIter() - ret = None - list(gen()) - self.assertEqual(ret, 42) - - def test_close_with_cleared_frame(self): - # See issue #17669. - # - # Create a stack of generators: outer() delegating to inner() - # delegating to innermost(). The key point is that the instance of - # inner is created first: this ensures that its frame appears before - # the instance of outer in the GC linked list. - # - # At the gc.collect call: - # - frame_clear is called on the inner_gen frame. - # - gen_dealloc is called on the outer_gen generator (the only - # reference is in the frame's locals). - # - gen_close is called on the outer_gen generator. - # - gen_close_iter is called to close the inner_gen generator, which - # in turn calls gen_close, and gen_yf. - # - # Previously, gen_yf would crash since inner_gen's frame had been - # cleared (and in particular f_stacktop was NULL). - - def innermost(): - yield - def inner(): - outer_gen = yield - yield from innermost() - def outer(): - inner_gen = yield - yield from inner_gen - - with disable_gc(): - inner_gen = inner() - outer_gen = outer() - outer_gen.send(None) - outer_gen.send(inner_gen) - outer_gen.send(outer_gen) - - del outer_gen - del inner_gen - gc_collect() - - def test_send_tuple_with_custom_generator(self): - # See issue #21209. - class MyGen: - def __iter__(self): - return self - def __next__(self): - return 42 - def send(self, what): - nonlocal v - v = what - return None - def outer(): - v = yield from MyGen() - g = outer() - next(g) - v = None - g.send((1, 2, 3, 4)) - self.assertEqual(v, (1, 2, 3, 4)) - - -def test_main(): - from test import support - test_classes = [TestPEP380Operation] - support.run_unittest(*test_classes) - - -if __name__ == '__main__': - test_main() diff --git a/textwrap/setup.py b/textwrap/setup.py deleted file mode 100644 index 484e2b46d..000000000 --- a/textwrap/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-textwrap', - version='3.4.2-1', - description='CPython textwrap module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['textwrap']) diff --git a/threading/setup.py b/threading/setup.py deleted file mode 100644 index f1a61f449..000000000 --- a/threading/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-threading', - version='0.1', - description='threading module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['threading']) diff --git a/time/setup.py b/time/setup.py deleted file mode 100644 index 6e044db58..000000000 --- a/time/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-time', - version='0.5', - description='time module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['time'], - install_requires=['micropython-ffilib']) diff --git a/time/test_strftime.py b/time/test_strftime.py deleted file mode 100644 index ad92b7115..000000000 --- a/time/test_strftime.py +++ /dev/null @@ -1,36 +0,0 @@ -from time import strftime - -# These tuples were generated using localtime() and gmtime() in CPython. -INPUT = ( - (2017, 1, 1, 23, 40, 39, 6, 222, 1), - (2010, 2, 28, 9, 59, 60, 1, 111, 0), - (2000, 3, 31, 1, 33, 0, 2, 44, 1), - (2020, 4, 30, 21, 22, 59, 3, 234, 0), - (1977, 5, 15, 23, 55, 1, 4, 123, 1), - (1940, 6, 11, 9, 21, 33, 5, 55, 0), - (1918, 7, 24, 6, 12, 44, 7, 71, 1), - (1800, 8, 17, 0, 59, 55, 3, 89, 0), - (2222, 9, 5, 1, 0, 4, 2, 255, 1), - (2017, 10, 10, 9, 1, 5, 6, 200, 0), - (2016, 11, 7, 18, 8, 16, 7, 100, 1), - (2001, 12, 2, 12, 19, 27, 1, 33, 0), -) - -# These values were generated using strftime() in CPython. -EXPECTED = ( - ('20170101234039'), - ('20100228095960'), - ('20000331013300'), - ('20200430212259'), - ('19770515235501'), - ('19400611092133'), - ('19180724061244'), - ('18000817005955'), - ('22220905010004'), - ('20171010090105'), - ('20161107180816'), - ('20011202121927'), -) - -for i in range(len(INPUT)): - assert strftime("%Y%m%d%H%M%S", INPUT[i]) == EXPECTED[i] diff --git a/timeit/setup.py b/timeit/setup.py deleted file mode 100644 index ec909a53e..000000000 --- a/timeit/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-timeit', - version='3.3.3-3', - description='CPython timeit module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['timeit'], - install_requires=['micropython-getopt', 'micropython-itertools', 'micropython-linecache', 'micropython-time', 'micropython-traceback']) diff --git a/trace/metadata.txt b/trace/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/trace/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/trace/setup.py b/trace/setup.py deleted file mode 100644 index b91042e40..000000000 --- a/trace/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-trace', - version='0.0.1', - description='Dummy trace module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['trace']) diff --git a/trace/trace.py b/trace/trace.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/traceback/setup.py b/traceback/setup.py deleted file mode 100644 index 8499f55c4..000000000 --- a/traceback/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-traceback', - version='0.3', - description='traceback module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['traceback']) diff --git a/tty/setup.py b/tty/setup.py deleted file mode 100644 index b1d9fc4f3..000000000 --- a/tty/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-tty', - version='1.0.1', - description='tty module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['tty']) diff --git a/types/setup.py b/types/setup.py deleted file mode 100644 index 41ad422ac..000000000 --- a/types/setup.py +++ /dev/null @@ -1,11 +0,0 @@ -from distutils.core import setup - -setup(name='micropython-types', - version='0.0.1', - description='CPython types module ported to MicroPython', - url='https://github.com/micropython/micropython/issues/405', - author='CPython Developers', - maintainer='MicroPython Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - py_modules=['types']) diff --git a/typing/metadata.txt b/typing/metadata.txt deleted file mode 100644 index 976088c8a..000000000 --- a/typing/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.0 diff --git a/typing/setup.py b/typing/setup.py deleted file mode 100644 index 2da0b6232..000000000 --- a/typing/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-typing', - version='0.0.0', - description='Dummy typing module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['typing']) diff --git a/typing/typing.py b/typing/typing.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/uaiohttpclient/setup.py b/uaiohttpclient/setup.py deleted file mode 100644 index 9da6c0452..000000000 --- a/uaiohttpclient/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-uaiohttpclient', - version='0.5.1', - description='HTTP client module for MicroPython uasyncio module', - long_description=open('README').read(), - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['uaiohttpclient']) diff --git a/uasyncio.core/example_call_soon.py b/uasyncio.core/example_call_soon.py deleted file mode 100644 index 7379144f2..000000000 --- a/uasyncio.core/example_call_soon.py +++ /dev/null @@ -1,16 +0,0 @@ -import uasyncio.core as asyncio -import time -import logging -logging.basicConfig(level=logging.DEBUG) -#asyncio.set_debug(True) - - -def cb(): - print("callback") - time.sleep(0.5) - loop.call_soon(cb) - - -loop = asyncio.get_event_loop() -loop.call_soon(cb) -loop.run_forever() diff --git a/uasyncio.core/metadata.txt b/uasyncio.core/metadata.txt deleted file mode 100644 index 21d581668..000000000 --- a/uasyncio.core/metadata.txt +++ /dev/null @@ -1,6 +0,0 @@ -srctype = micropython-lib -type = package -version = 2.0 -author = Paul Sokolovsky -desc = Lightweight asyncio-like library for MicroPython, built around native Python coroutines. (Core event loop). -long_desc = Lightweight asyncio-like library for MicroPython, built around native Python coroutines. (Core event loop). diff --git a/uasyncio.core/setup.py b/uasyncio.core/setup.py deleted file mode 100644 index d7c468099..000000000 --- a/uasyncio.core/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-uasyncio.core', - version='2.0', - description='Lightweight asyncio-like library for MicroPython, built around native Python coroutines. (Core event loop).', - long_description='Lightweight asyncio-like library for MicroPython, built around native Python coroutines. (Core event loop).', - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['uasyncio']) diff --git a/uasyncio.core/test_cancel.py b/uasyncio.core/test_cancel.py deleted file mode 100644 index 495cd6a06..000000000 --- a/uasyncio.core/test_cancel.py +++ /dev/null @@ -1,73 +0,0 @@ -import time -try: - import uasyncio.core as asyncio - is_uasyncio = True -except ImportError: - import asyncio - is_uasyncio = False -import logging -#logging.basicConfig(level=logging.DEBUG) -#asyncio.set_debug(True) - - -output = [] -cancelled = False - -def print1(msg): - print(msg) - output.append(msg) - -def looper1(iters): - global cancelled - try: - for i in range(iters): - print1("ping1") - # sleep() isn't properly cancellable - #yield from asyncio.sleep(1.0) - t = time.time() - while time.time() - t < 1: - yield from asyncio.sleep(0) - return 10 - except asyncio.CancelledError: - print1("cancelled") - cancelled = True - -def looper2(iters): - for i in range(iters): - print1("ping2") - # sleep() isn't properly cancellable - #yield from asyncio.sleep(1.0) - t = time.time() - while time.time() - t < 1: - yield from asyncio.sleep(0) - return 10 - - -def run_to(): - coro = looper1(10) - task = loop.create_task(coro) - yield from asyncio.sleep(3) - if is_uasyncio: - asyncio.cancel(coro) - else: - task.cancel() - # Need another eventloop iteration for cancellation to be actually - # processed and to see side effects of the cancellation. - yield from asyncio.sleep(0) - assert cancelled - - coro = looper2(10) - task = loop.create_task(coro) - yield from asyncio.sleep(2) - if is_uasyncio: - asyncio.cancel(coro) - else: - task.cancel() - yield from asyncio.sleep(0) - - # Once saw 3 ping3's output on CPython 3.5.2 - assert output == ['ping1', 'ping1', 'ping1', 'cancelled', 'ping2', 'ping2'] - - -loop = asyncio.get_event_loop() -loop.run_until_complete(run_to()) diff --git a/uasyncio.core/test_cb_args.py b/uasyncio.core/test_cb_args.py deleted file mode 100644 index 8bf80a6b7..000000000 --- a/uasyncio.core/test_cb_args.py +++ /dev/null @@ -1,16 +0,0 @@ -try: - import uasyncio.core as asyncio -except: - import asyncio - - -def cb(a, b): - assert a == "test" - assert b == "test2" - loop.stop() - - -loop = asyncio.get_event_loop() -loop.call_soon(cb, "test", "test2") -loop.run_forever() -print("OK") diff --git a/uasyncio.core/test_fair_schedule.py b/uasyncio.core/test_fair_schedule.py deleted file mode 100644 index e4f8e38d2..000000000 --- a/uasyncio.core/test_fair_schedule.py +++ /dev/null @@ -1,39 +0,0 @@ -# Test that uasyncio scheduling is fair, i.e. gives all -# coroutines equal chance to run (this specifically checks -# round-robin scheduling). -import uasyncio.core as asyncio - - -COROS = 10 -ITERS = 20 - - -result = [] -test_finished = False - - -async def coro(n): - for i in range(ITERS): - result.append(n) - yield - - -async def done(): - global test_finished - while True: - if len(result) == COROS * ITERS: - #print(result) - assert result == list(range(COROS)) * ITERS - test_finished = True - return - yield - - -loop = asyncio.get_event_loop() - -for n in range(COROS): - loop.create_task(coro(n)) - -loop.run_until_complete(done()) - -assert test_finished diff --git a/uasyncio.core/test_full_wait.py b/uasyncio.core/test_full_wait.py deleted file mode 100644 index 17af6f26d..000000000 --- a/uasyncio.core/test_full_wait.py +++ /dev/null @@ -1,50 +0,0 @@ -# Test that coros scheduled to run at some time don't run prematurely -# in case of I/O completion before that. -import uasyncio.core as uasyncio -import logging -logging.basicConfig(level=logging.DEBUG) -#uasyncio.set_debug(True) - - -class MockEventLoop(uasyncio.EventLoop): - - def __init__(self): - super().__init__() - self.t = 0 - self.msgs = [] - - def time(self): - return self.t - - def pass_time(self, delta): - self.t += delta - - def wait(self, delay): - #print("%d: wait(%d)" % (self.t, delay)) - self.pass_time(100) - - if self.t == 100: - def cb_1st(): - self.msgs.append("I should be run first, time: %s" % self.time()) - self.call_soon(cb_1st) - - if self.t == 1000: - raise StopIteration - - -loop = MockEventLoop() - -def cb_2nd(): - loop.msgs.append("I should be run second, time: %s" % loop.time()) - -loop.call_later_ms(500, cb_2nd) - -try: - loop.run_forever() -except StopIteration: - pass - -print(loop.msgs) -# .wait() is now called on each loop iteration, and for our mock case, it means that -# at the time of running, self.time() will be skewed by 100 virtual time units. -assert loop.msgs == ['I should be run first, time: 100', 'I should be run second, time: 500'], str(loop.msgs) diff --git a/uasyncio.core/test_wait_for.py b/uasyncio.core/test_wait_for.py deleted file mode 100644 index 0e156387f..000000000 --- a/uasyncio.core/test_wait_for.py +++ /dev/null @@ -1,46 +0,0 @@ -try: - import uasyncio.core as asyncio -except ImportError: - import asyncio -import logging -#logging.basicConfig(level=logging.DEBUG) -#asyncio.set_debug(True) - - -def looper(iters): - for i in range(iters): - print("ping") - yield from asyncio.sleep(1.0) - return 10 - - -def run_to(): - try: - ret = yield from asyncio.wait_for(looper(2), 1) - print("result:", ret) - assert False - except asyncio.TimeoutError: - print("Coro timed out") - - print("=================") - - try: - ret = yield from asyncio.wait_for(looper(2), 2) - print("result:", ret) - assert False - except asyncio.TimeoutError: - print("Coro timed out") - - print("=================") - - try: - ret = yield from asyncio.wait_for(looper(2), 3) - print("result:", ret) - except asyncio.TimeoutError: - print("Coro timed out") - assert False - - -loop = asyncio.get_event_loop() -loop.run_until_complete(run_to()) -loop.run_until_complete(asyncio.sleep(1)) diff --git a/uasyncio.core/uasyncio/core.py b/uasyncio.core/uasyncio/core.py deleted file mode 100644 index 77fdb7a27..000000000 --- a/uasyncio.core/uasyncio/core.py +++ /dev/null @@ -1,315 +0,0 @@ -import utime as time -import utimeq -import ucollections - - -type_gen = type((lambda: (yield))()) - -DEBUG = 0 -log = None - -def set_debug(val): - global DEBUG, log - DEBUG = val - if val: - import logging - log = logging.getLogger("uasyncio.core") - - -class CancelledError(Exception): - pass - - -class TimeoutError(CancelledError): - pass - - -class EventLoop: - - def __init__(self, runq_len=16, waitq_len=16): - self.runq = ucollections.deque((), runq_len, True) - self.waitq = utimeq.utimeq(waitq_len) - # Current task being run. Task is a top-level coroutine scheduled - # in the event loop (sub-coroutines executed transparently by - # yield from/await, event loop "doesn't see" them). - self.cur_task = None - - def time(self): - return time.ticks_ms() - - def create_task(self, coro): - # CPython 3.4.2 - self.call_later_ms(0, coro) - # CPython asyncio incompatibility: we don't return Task object - - def call_soon(self, callback, *args): - if __debug__ and DEBUG: - log.debug("Scheduling in runq: %s", (callback, args)) - self.runq.append(callback) - if not isinstance(callback, type_gen): - self.runq.append(args) - - def call_later(self, delay, callback, *args): - self.call_at_(time.ticks_add(self.time(), int(delay * 1000)), callback, args) - - def call_later_ms(self, delay, callback, *args): - if not delay: - return self.call_soon(callback, *args) - self.call_at_(time.ticks_add(self.time(), delay), callback, args) - - def call_at_(self, time, callback, args=()): - if __debug__ and DEBUG: - log.debug("Scheduling in waitq: %s", (time, callback, args)) - self.waitq.push(time, callback, args) - - def wait(self, delay): - # Default wait implementation, to be overriden in subclasses - # with IO scheduling - if __debug__ and DEBUG: - log.debug("Sleeping for: %s", delay) - time.sleep_ms(delay) - - def run_forever(self): - cur_task = [0, 0, 0] - while True: - # Expire entries in waitq and move them to runq - tnow = self.time() - while self.waitq: - t = self.waitq.peektime() - delay = time.ticks_diff(t, tnow) - if delay > 0: - break - self.waitq.pop(cur_task) - if __debug__ and DEBUG: - log.debug("Moving from waitq to runq: %s", cur_task[1]) - self.call_soon(cur_task[1], *cur_task[2]) - - # Process runq - l = len(self.runq) - if __debug__ and DEBUG: - log.debug("Entries in runq: %d", l) - while l: - cb = self.runq.popleft() - l -= 1 - args = () - if not isinstance(cb, type_gen): - args = self.runq.popleft() - l -= 1 - if __debug__ and DEBUG: - log.info("Next callback to run: %s", (cb, args)) - cb(*args) - continue - - if __debug__ and DEBUG: - log.info("Next coroutine to run: %s", (cb, args)) - self.cur_task = cb - delay = 0 - try: - if args is (): - ret = next(cb) - else: - ret = cb.send(*args) - if __debug__ and DEBUG: - log.info("Coroutine %s yield result: %s", cb, ret) - if isinstance(ret, SysCall1): - arg = ret.arg - if isinstance(ret, SleepMs): - delay = arg - elif isinstance(ret, IORead): - cb.pend_throw(False) - self.add_reader(arg, cb) - continue - elif isinstance(ret, IOWrite): - cb.pend_throw(False) - self.add_writer(arg, cb) - continue - elif isinstance(ret, IOReadDone): - self.remove_reader(arg) - elif isinstance(ret, IOWriteDone): - self.remove_writer(arg) - elif isinstance(ret, StopLoop): - return arg - else: - assert False, "Unknown syscall yielded: %r (of type %r)" % (ret, type(ret)) - elif isinstance(ret, type_gen): - self.call_soon(ret) - elif isinstance(ret, int): - # Delay - delay = ret - elif ret is None: - # Just reschedule - pass - elif ret is False: - # Don't reschedule - continue - else: - assert False, "Unsupported coroutine yield value: %r (of type %r)" % (ret, type(ret)) - except StopIteration as e: - if __debug__ and DEBUG: - log.debug("Coroutine finished: %s", cb) - continue - except CancelledError as e: - if __debug__ and DEBUG: - log.debug("Coroutine cancelled: %s", cb) - continue - # Currently all syscalls don't return anything, so we don't - # need to feed anything to the next invocation of coroutine. - # If that changes, need to pass that value below. - if delay: - self.call_later_ms(delay, cb) - else: - self.call_soon(cb) - - # Wait until next waitq task or I/O availability - delay = 0 - if not self.runq: - delay = -1 - if self.waitq: - tnow = self.time() - t = self.waitq.peektime() - delay = time.ticks_diff(t, tnow) - if delay < 0: - delay = 0 - self.wait(delay) - - def run_until_complete(self, coro): - def _run_and_stop(): - yield from coro - yield StopLoop(0) - self.call_soon(_run_and_stop()) - self.run_forever() - - def stop(self): - self.call_soon((lambda: (yield StopLoop(0)))()) - - def close(self): - pass - - -class SysCall: - - def __init__(self, *args): - self.args = args - - def handle(self): - raise NotImplementedError - -# Optimized syscall with 1 arg -class SysCall1(SysCall): - - def __init__(self, arg): - self.arg = arg - -class StopLoop(SysCall1): - pass - -class IORead(SysCall1): - pass - -class IOWrite(SysCall1): - pass - -class IOReadDone(SysCall1): - pass - -class IOWriteDone(SysCall1): - pass - - -_event_loop = None -_event_loop_class = EventLoop -def get_event_loop(runq_len=16, waitq_len=16): - global _event_loop - if _event_loop is None: - _event_loop = _event_loop_class(runq_len, waitq_len) - return _event_loop - -def sleep(secs): - yield int(secs * 1000) - -# Implementation of sleep_ms awaitable with zero heap memory usage -class SleepMs(SysCall1): - - def __init__(self): - self.v = None - self.arg = None - - def __call__(self, arg): - self.v = arg - #print("__call__") - return self - - def __iter__(self): - #print("__iter__") - return self - - def __next__(self): - if self.v is not None: - #print("__next__ syscall enter") - self.arg = self.v - self.v = None - return self - #print("__next__ syscall exit") - _stop_iter.__traceback__ = None - raise _stop_iter - -_stop_iter = StopIteration() -sleep_ms = SleepMs() - - -def cancel(coro): - prev = coro.pend_throw(CancelledError()) - if prev is False: - _event_loop.call_soon(coro) - - -class TimeoutObj: - def __init__(self, coro): - self.coro = coro - - -def wait_for_ms(coro, timeout): - - def waiter(coro, timeout_obj): - res = yield from coro - if __debug__ and DEBUG: - log.debug("waiter: cancelling %s", timeout_obj) - timeout_obj.coro = None - return res - - def timeout_func(timeout_obj): - if timeout_obj.coro: - if __debug__ and DEBUG: - log.debug("timeout_func: cancelling %s", timeout_obj.coro) - prev = timeout_obj.coro.pend_throw(TimeoutError()) - #print("prev pend", prev) - if prev is False: - _event_loop.call_soon(timeout_obj.coro) - - timeout_obj = TimeoutObj(_event_loop.cur_task) - _event_loop.call_later_ms(timeout, timeout_func, timeout_obj) - return (yield from waiter(coro, timeout_obj)) - - -def wait_for(coro, timeout): - return wait_for_ms(coro, int(timeout * 1000)) - - -def coroutine(f): - return f - -# -# The functions below are deprecated in uasyncio, and provided only -# for compatibility with CPython asyncio -# - -def ensure_future(coro, loop=_event_loop): - _event_loop.call_soon(coro) - # CPython asyncio incompatibility: we don't return Task object - return coro - - -# CPython asyncio incompatibility: Task is a function, not a class (for efficiency) -def Task(coro, loop=_event_loop): - # Same as async() - _event_loop.call_soon(coro) diff --git a/uasyncio.queues/metadata.txt b/uasyncio.queues/metadata.txt deleted file mode 100644 index 06127d03a..000000000 --- a/uasyncio.queues/metadata.txt +++ /dev/null @@ -1,5 +0,0 @@ -srctype = micropython-lib -type = package -version = 0.1.2 -long_desc = Port of asyncio.queues to uasyncio. -depends = uasyncio.core, collections.deque diff --git a/uasyncio.queues/setup.py b/uasyncio.queues/setup.py deleted file mode 100644 index e90c5532b..000000000 --- a/uasyncio.queues/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-uasyncio.queues', - version='0.1.2', - description='uasyncio.queues module for MicroPython', - long_description='Port of asyncio.queues to uasyncio.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['uasyncio'], - install_requires=['micropython-uasyncio.core', 'micropython-collections.deque']) diff --git a/uasyncio.queues/tests/test.py b/uasyncio.queues/tests/test.py deleted file mode 100644 index 72b3d85c3..000000000 --- a/uasyncio.queues/tests/test.py +++ /dev/null @@ -1,57 +0,0 @@ -from unittest import TestCase, run_class -import sys -sys.path.insert(0, '../uasyncio') -import queues - - -class QueueTestCase(TestCase): - - def _val(self, gen): - """Returns val from generator.""" - while True: - try: - gen.send(None) - except StopIteration as e: - return e.value - - def test_get_put(self): - q = queues.Queue(maxsize=1) - self._val(q.put(42)) - self.assertEqual(self._val(q.get()), 42) - - def test_get_put_nowait(self): - q = queues.Queue(maxsize=1) - q.put_nowait(12) - try: - q.put_nowait(42) - self.assertTrue(False) - except Exception as e: - self.assertEqual(type(e), queues.QueueFull) - self.assertEqual(q.get_nowait(), 12) - try: - q.get_nowait() - self.assertTrue(False) - except Exception as e: - self.assertEqual(type(e), queues.QueueEmpty) - - def test_qsize(self): - q = queues.Queue() - for n in range(10): - q.put_nowait(10) - self.assertEqual(q.qsize(), 10) - - def test_empty(self): - q = queues.Queue() - self.assertTrue(q.empty()) - q.put_nowait(10) - self.assertFalse(q.empty()) - - def test_full(self): - q = queues.Queue(maxsize=1) - self.assertFalse(q.full()) - q.put_nowait(10) - self.assertTrue(q.full()) - - -if __name__ == '__main__': - run_class(QueueTestCase) diff --git a/uasyncio.queues/uasyncio/queues.py b/uasyncio.queues/uasyncio/queues.py deleted file mode 100644 index 04918ae5c..000000000 --- a/uasyncio.queues/uasyncio/queues.py +++ /dev/null @@ -1,94 +0,0 @@ -from collections.deque import deque -from uasyncio.core import sleep - - -class QueueEmpty(Exception): - """Exception raised by get_nowait().""" - - -class QueueFull(Exception): - """Exception raised by put_nowait().""" - - -class Queue: - """A queue, useful for coordinating producer and consumer coroutines. - - If maxsize is less than or equal to zero, the queue size is infinite. If it - is an integer greater than 0, then "yield from put()" will block when the - queue reaches maxsize, until an item is removed by get(). - - Unlike the standard library Queue, you can reliably know this Queue's size - with qsize(), since your single-threaded uasyncio application won't be - interrupted between calling qsize() and doing an operation on the Queue. - """ - _attempt_delay = 0.1 - - def __init__(self, maxsize=0): - self.maxsize = maxsize - self._queue = deque() - - def _get(self): - return self._queue.popleft() - - def get(self): - """Returns generator, which can be used for getting (and removing) - an item from a queue. - - Usage:: - - item = yield from queue.get() - """ - while not self._queue: - yield from sleep(self._attempt_delay) - return self._get() - - def get_nowait(self): - """Remove and return an item from the queue. - - Return an item if one is immediately available, else raise QueueEmpty. - """ - if not self._queue: - raise QueueEmpty() - return self._get() - - def _put(self, val): - self._queue.append(val) - - def put(self, val): - """Returns generator which can be used for putting item in a queue. - - Usage:: - - yield from queue.put(item) - """ - while self.qsize() >= self.maxsize and self.maxsize: - yield from sleep(self._attempt_delay) - self._put(val) - - def put_nowait(self, val): - """Put an item into the queue without blocking. - - If no free slot is immediately available, raise QueueFull. - """ - if self.qsize() >= self.maxsize and self.maxsize: - raise QueueFull() - self._put(val) - - def qsize(self): - """Number of items in the queue.""" - return len(self._queue) - - def empty(self): - """Return True if the queue is empty, False otherwise.""" - return not self._queue - - def full(self): - """Return True if there are maxsize items in the queue. - - Note: if the Queue was initialized with maxsize=0 (the default), - then full() is never True. - """ - if self.maxsize <= 0: - return False - else: - return self.qsize() >= self.maxsize diff --git a/uasyncio.synchro/example_lock.py b/uasyncio.synchro/example_lock.py deleted file mode 100644 index 863f93384..000000000 --- a/uasyncio.synchro/example_lock.py +++ /dev/null @@ -1,27 +0,0 @@ -try: - import uasyncio.core as asyncio - from uasyncio.synchro import Lock -except ImportError: - import asyncio - from asyncio import Lock - - -def task(i, lock): - print(lock) - while 1: - yield from lock.acquire() - print("Acquired lock in task", i) - yield from asyncio.sleep(0.5) -# yield lock.release() - lock.release() - - -loop = asyncio.get_event_loop() - -lock = Lock() - -loop.create_task(task(1, lock)) -loop.create_task(task(2, lock)) -loop.create_task(task(3, lock)) - -loop.run_forever() diff --git a/uasyncio.synchro/metadata.txt b/uasyncio.synchro/metadata.txt deleted file mode 100644 index 6874b0765..000000000 --- a/uasyncio.synchro/metadata.txt +++ /dev/null @@ -1,5 +0,0 @@ -srctype = micropython-lib -type = package -version = 0.1.1 -desc = Synchronization primitives for uasyncio. -depends = uasyncio.core diff --git a/uasyncio.synchro/setup.py b/uasyncio.synchro/setup.py deleted file mode 100644 index d978369b8..000000000 --- a/uasyncio.synchro/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-uasyncio.synchro', - version='0.1.1', - description='Synchronization primitives for uasyncio.', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['uasyncio'], - install_requires=['micropython-uasyncio.core']) diff --git a/uasyncio.synchro/uasyncio/synchro.py b/uasyncio.synchro/uasyncio/synchro.py deleted file mode 100644 index 62cd93cdd..000000000 --- a/uasyncio.synchro/uasyncio/synchro.py +++ /dev/null @@ -1,28 +0,0 @@ -from uasyncio import core - -class Lock: - - def __init__(self): - self.locked = False - self.wlist = [] - - def release(self): - assert self.locked - self.locked = False - if self.wlist: - #print(self.wlist) - coro = self.wlist.pop(0) - core.get_event_loop().call_soon(coro) - - def acquire(self): - # As release() is not coro, assume we just released and going to acquire again - # so, yield first to let someone else to acquire it first - yield - #print("acquire:", self.locked) - while 1: - if not self.locked: - self.locked = True - return True - #print("putting", core.get_event_loop().cur_task, "on waiting list") - self.wlist.append(core.get_event_loop().cur_task) - yield False diff --git a/uasyncio.udp/example_dns_junk.py b/uasyncio.udp/example_dns_junk.py deleted file mode 100644 index ce651fb59..000000000 --- a/uasyncio.udp/example_dns_junk.py +++ /dev/null @@ -1,26 +0,0 @@ -# This example is intended to run with dnsmasq running on localhost -# (Ubuntu comes configured like that by default). Dnsmasq, receiving -# some junk, is still kind to reply something back, which we employ -# here. -import uasyncio -import uasyncio.udp -import usocket - -def udp_req(addr): - s = uasyncio.udp.socket() - print(s) - yield from uasyncio.udp.sendto(s, b"!eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", addr) - try: - resp = yield from uasyncio.wait_for(uasyncio.udp.recv(s, 1024), 1) - print(resp) - except uasyncio.TimeoutError: - print("timed out") - - -import logging -logging.basicConfig(level=logging.INFO) - -addr = usocket.getaddrinfo("127.0.0.1", 53)[0][-1] -loop = uasyncio.get_event_loop() -loop.run_until_complete(udp_req(addr)) -loop.close() diff --git a/uasyncio.udp/metadata.txt b/uasyncio.udp/metadata.txt deleted file mode 100644 index c791cef1b..000000000 --- a/uasyncio.udp/metadata.txt +++ /dev/null @@ -1,6 +0,0 @@ -srctype = micropython-lib -type = package -version = 0.1.1 -author = Paul Sokolovsky -desc = UDP support for MicroPython's uasyncio -depends = uasyncio diff --git a/uasyncio.udp/setup.py b/uasyncio.udp/setup.py deleted file mode 100644 index 95ce6a027..000000000 --- a/uasyncio.udp/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-uasyncio.udp', - version='0.1.1', - description="UDP support for MicroPython's uasyncio", - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['uasyncio'], - install_requires=['micropython-uasyncio']) diff --git a/uasyncio.udp/uasyncio/udp.py b/uasyncio.udp/uasyncio/udp.py deleted file mode 100644 index 5987bf7d2..000000000 --- a/uasyncio.udp/uasyncio/udp.py +++ /dev/null @@ -1,57 +0,0 @@ -import usocket -from uasyncio import core - - -DEBUG = 0 -log = None - -def set_debug(val): - global DEBUG, log - DEBUG = val - if val: - import logging - log = logging.getLogger("uasyncio.udp") - -def socket(af=usocket.AF_INET): - s = usocket.socket(af, usocket.SOCK_DGRAM) - s.setblocking(False) - return s - -def recv(s, n): - try: - yield core.IORead(s) - return s.recv(n) - except: - #print("recv: exc, cleaning up") - #print(uasyncio.core._event_loop.objmap, uasyncio.core._event_loop.poller) - #uasyncio.core._event_loop.poller.dump() - yield core.IOReadDone(s) - #print(uasyncio.core._event_loop.objmap) - #uasyncio.core._event_loop.poller.dump() - raise - -def recvfrom(s, n): - try: - yield core.IORead(s) - return s.recvfrom(n) - except: - #print("recv: exc, cleaning up") - #print(uasyncio.core._event_loop.objmap, uasyncio.core._event_loop.poller) - #uasyncio.core._event_loop.poller.dump() - yield core.IOReadDone(s) - #print(uasyncio.core._event_loop.objmap) - #uasyncio.core._event_loop.poller.dump() - raise - -def sendto(s, buf, addr=None): - while 1: - res = s.sendto(buf, addr) - #print("send res:", res) - if res == len(buf): - return - print("sendto: IOWrite") - yield core.IOWrite(s) - -def close(s): - yield core.IOReadDone(s) - s.close() diff --git a/uasyncio.websocket.server/example_websock.py b/uasyncio.websocket.server/example_websock.py deleted file mode 100644 index fd08729dc..000000000 --- a/uasyncio.websocket.server/example_websock.py +++ /dev/null @@ -1,27 +0,0 @@ -import uasyncio -from uasyncio.websocket.server import WSReader, WSWriter - - -def echo(reader, writer): - # Consume GET line - yield from reader.readline() - - reader = yield from WSReader(reader, writer) - writer = WSWriter(reader, writer) - - while 1: - l = yield from reader.read(256) - print(l) - if l == b"\r": - await writer.awrite(b"\r\n") - else: - await writer.awrite(l) - - -import logging -#logging.basicConfig(level=logging.INFO) -logging.basicConfig(level=logging.DEBUG) -loop = uasyncio.get_event_loop() -loop.create_task(uasyncio.start_server(echo, "127.0.0.1", 8081)) -loop.run_forever() -loop.close() diff --git a/uasyncio.websocket.server/setup.py b/uasyncio.websocket.server/setup.py deleted file mode 100644 index 67573be26..000000000 --- a/uasyncio.websocket.server/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-uasyncio.websocket.server', - version='0.1', - description='uasyncio.websocket.server module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['uasyncio.websocket'], - install_requires=['micropython-uasyncio']) diff --git a/uasyncio.websocket.server/uasyncio/websocket/server.py b/uasyncio.websocket.server/uasyncio/websocket/server.py deleted file mode 100644 index 046b071ea..000000000 --- a/uasyncio.websocket.server/uasyncio/websocket/server.py +++ /dev/null @@ -1,63 +0,0 @@ -import uasyncio -import uhashlib, ubinascii -import websocket - - -def make_respkey(webkey): - d = uhashlib.sha1(webkey) - d.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11") - respkey = d.digest() - respkey = ubinascii.b2a_base64(respkey) #[:-1] - # Return with trailing "\n". - return respkey - - -class WSWriter: - - def __init__(self, reader, writer): - # Reader is passed for symmetry with WSReader() and ignored. - self.s = writer - - async def awrite(self, data): - assert len(data) < 126 - await self.s.awrite(b"\x81") - await self.s.awrite(bytes([len(data)])) - await self.s.awrite(data) - - -def WSReader(reader, writer): - - webkey = None - while 1: - l = yield from reader.readline() - print(l) - if not l: - raise ValueError() - if l == b"\r\n": - break - if l.startswith(b'Sec-WebSocket-Key'): - webkey = l.split(b":", 1)[1] - webkey = webkey.strip() - - if not webkey: - raise ValueError("Not a websocker request") - - respkey = make_respkey(webkey) - - await writer.awrite(b"""\ -HTTP/1.1 101 Switching Protocols\r -Upgrade: websocket\r -Connection: Upgrade\r -Sec-WebSocket-Accept: """) - await writer.awrite(respkey) - # This will lead to "\n\r\n" being written. Not exactly - # "\r\n\r\n", but browsers seem to eat it. - await writer.awrite("\r\n") - #await writer.awrite("\r\n\r\n") - - print("Finished webrepl handshake") - - ws = websocket.websocket(reader.ios) - rws = uasyncio.StreamReader(reader.ios, ws) - - return rws diff --git a/uasyncio/README.rst b/uasyncio/README.rst deleted file mode 100644 index fb625b0f1..000000000 --- a/uasyncio/README.rst +++ /dev/null @@ -1,43 +0,0 @@ -uasyncio -======== - -uasyncio is MicroPython's asynchronous sheduling library, roughly -modeled after CPython's asyncio. - -uasyncio doesn't use naive always-iterating scheduling algorithm, -but performs a real time-based scheduling, which allows it (and -thus the whole system) to sleep when there is nothing to do (actual -implementation of that depends on I/O scheduling algorithm which -actually performs the wait operation). - -Major conceptual differences to asyncio: - -* Avoids defining a notion of Future, and especially wrapping coroutines - in Futures, like CPython asyncio does. uasyncio works directly with - coroutines (and callbacks). -* Methods provided are more consistently coroutines. -* uasyncio uses wrap-around millisecond timebase (as native to all - MicroPython ports.) -* Instead of single large package, number of subpackages are provided - (each installable separately). - -Specific differences: - -* For millisecond scheduling, ``loop.call_later_ms()`` and - ``uasyncio.sleep_ms()`` are provided. -* As there's no monotonic time, ``loop.call_at()`` is not provided. - Instead, there's ``loop.call_at_()`` which is considered an internal - function and has slightly different signature. -* ``call_*`` funcions don't return Handle and callbacks scheduled by - them aren't cancellable. If they need to be cancellable, they should - accept an object as an argument, and a "cancel" flag should be set - in the object, for a callback to test. -* ``Future`` object is not available. -* ``ensure_future()`` and ``Task()`` perform just scheduling operations - and return a native coroutine, not Future/Task objects. -* Some other functions are not (yet) implemented. -* StreamWriter method(s) are coroutines. While in CPython asyncio, - StreamWriter.write() is a normal function (which potentially buffers - unlimited amount of data), uasyncio offers coroutine StreamWriter.awrite() - instead. Also, both StreamReader and StreamWriter have .aclose() - coroutine method. diff --git a/uasyncio/README.test b/uasyncio/README.test deleted file mode 100644 index 89cd7ecd6..000000000 --- a/uasyncio/README.test +++ /dev/null @@ -1,45 +0,0 @@ -Testing and Validating ----------------------- - -To test uasyncio correctness and performance, HTTP server samples can be -used. The simplest test is with test_http_server.py and Apache Benchmark -(ab). In one window, run: - -micropython -O test_http_server.py - -(-O is needed to short-circuit debug logging calls.) - -In another: - -ab -n10000 -c10 http://localhost:8081/ - -ab tests that all responses have the same length, but doesn't check -content. test_http_server.py also serves very short, static reply. - - -For more heavy testing, test_http_server_heavy.py is provided. It serves -large response split among several async writes. It is also dynamic - -includes incrementing counter, so each response will be different. The -response size generates is more 4Mb, because under Linux, socket writes -can buffer up to 4Mb of content (this appear to be controlled by -/proc/sys/net/ipv4/tcp_wmem and not /proc/sys/net/core/wmem_default). -test_http_server_heavy.py also includes (trivial) handling of -client-induced errors like EPIPE and ECONNRESET. To validate content -served, a post-hook script for "boom" tool -(https://github.com/tarekziade/boom) is provided. - -Before start, you may want to bump .listen() value in uasyncio/__init__.py -from default 10 to at least 30. - -Start: - -micropython -X heapsize=300000000 -O test_http_server_heavy.py - -(Yes, that's 300Mb of heap - we'll be serving 4+Mb of content with 30 -concurrent connections). - -And: - -PYTHONPATH=. boom -n1000 -c30 http://localhost:8081 --post-hook=boom_uasyncio.validate - -There should be no Python exceptions in the output. diff --git a/uasyncio/benchmark/boom_uasyncio.py b/uasyncio/benchmark/boom_uasyncio.py deleted file mode 100644 index 9f2654aaf..000000000 --- a/uasyncio/benchmark/boom_uasyncio.py +++ /dev/null @@ -1,38 +0,0 @@ -# -# This is validation script for "boom" tool https://github.com/tarekziade/boom -# To use it: -# -# boom -n1000 --post-hook=boom_uasyncio.validate -# -# Note that if you'll use other -n value, you should update NUM_REQS below -# to match. -# - -NUM_REQS = 1000 -seen = [] -cnt = 0 - -def validate(resp): - global cnt - t = resp.text - l = t.split("\r\n", 1)[0] - no = int(l.split()[1]) - seen.append(no) - c = t.count(l + "\r\n") - assert c == 400101, str(c) - assert t.endswith("=== END ===") - - cnt += 1 - if cnt == NUM_REQS: - seen.sort() - print - print seen - print - el = None - for i in seen: - if el is None: - el = i - else: - el += 1 - assert i == el - return resp diff --git a/uasyncio/benchmark/test-ab-medium.sh b/uasyncio/benchmark/test-ab-medium.sh deleted file mode 100755 index 7d5edcca1..000000000 --- a/uasyncio/benchmark/test-ab-medium.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/sh -# -# This in one-shot scripts to test "light load" uasyncio HTTP server using -# Apache Bench (ab). -# - -#python3.4.2 test_http_server_light.py & -#micropython -O test_http_server_light.py & - -#python3.4.2 test_http_server_medium.py & -micropython -O -X heapsize=200wK test_http_server_medium.py & - -sleep 1 - -ab -n10000 -c100 http://127.0.0.1:8081/ - -kill %1 diff --git a/uasyncio/benchmark/test-boom-heavy.sh b/uasyncio/benchmark/test-boom-heavy.sh deleted file mode 100755 index a977806a5..000000000 --- a/uasyncio/benchmark/test-boom-heavy.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/sh -# -# This in one-shot scripts to test "heavy load" uasyncio HTTP server using -# Boom tool https://github.com/tarekziade/boom . -# -# Note that this script doesn't test performance, but rather test functional -# correctness of uasyncio server implementation, while serving large amounts -# of data (guaranteedly more than a socket buffer). Thus, this script should -# not be used for benchmarking. -# - -if [ ! -d .venv-boom ]; then - virtualenv .venv-boom - . .venv-boom/bin/activate - # PyPI currently has 0.8 which is too old - #pip install boom - pip install git+https://github.com/tarekziade/boom -else - . .venv-boom/bin/activate -fi - - -micropython -X heapsize=300000000 -O test_http_server_heavy.py & -sleep 1 - -PYTHONPATH=. boom -n1000 -c30 http://localhost:8081 --post-hook=boom_uasyncio.validate - -kill %1 diff --git a/uasyncio/benchmark/test_http_server_heavy.py b/uasyncio/benchmark/test_http_server_heavy.py deleted file mode 100644 index fd8fd33dc..000000000 --- a/uasyncio/benchmark/test_http_server_heavy.py +++ /dev/null @@ -1,40 +0,0 @@ -import uasyncio as asyncio -import signal -import errno - - -cnt = 0 - -@asyncio.coroutine -def serve(reader, writer): - global cnt - #s = "Hello.\r\n" - s = "Hello. %07d\r\n" % cnt - cnt += 1 - yield from reader.read() - yield from writer.awrite("HTTP/1.0 200 OK\r\n\r\n") - try: - yield from writer.awrite(s) - yield from writer.awrite(s * 100) - yield from writer.awrite(s * 400000) - yield from writer.awrite("=== END ===") - except OSError as e: - if e.args[0] == errno.EPIPE: - print("EPIPE") - elif e.args[0] == errno.ECONNRESET: - print("ECONNRESET") - else: - raise - finally: - yield from writer.aclose() - - -import logging -logging.basicConfig(level=logging.INFO) -#logging.basicConfig(level=logging.DEBUG) -signal.signal(signal.SIGPIPE, signal.SIG_IGN) -loop = asyncio.get_event_loop() -#mem_info() -loop.call_soon(asyncio.start_server(serve, "0.0.0.0", 8081, backlog=100)) -loop.run_forever() -loop.close() diff --git a/uasyncio/benchmark/test_http_server_light.py b/uasyncio/benchmark/test_http_server_light.py deleted file mode 100644 index 33db55ec1..000000000 --- a/uasyncio/benchmark/test_http_server_light.py +++ /dev/null @@ -1,21 +0,0 @@ -import uasyncio as asyncio - - -@asyncio.coroutine -def serve(reader, writer): - #print(reader, writer) - #print("================") - yield from reader.read(512) - yield from writer.awrite("HTTP/1.0 200 OK\r\n\r\nHello.\r\n") - yield from writer.aclose() - #print("Finished processing request") - - -import logging -#logging.basicConfig(level=logging.INFO) -logging.basicConfig(level=logging.DEBUG) -loop = asyncio.get_event_loop() -#mem_info() -loop.create_task(asyncio.start_server(serve, "127.0.0.1", 8081, backlog=100)) -loop.run_forever() -loop.close() diff --git a/uasyncio/benchmark/test_http_server_medium.py b/uasyncio/benchmark/test_http_server_medium.py deleted file mode 100644 index cc42c03a6..000000000 --- a/uasyncio/benchmark/test_http_server_medium.py +++ /dev/null @@ -1,22 +0,0 @@ -import uasyncio as asyncio - -resp = "HTTP/1.0 200 OK\r\n\r\n" + "Hello.\r\n" * 1500 - -@asyncio.coroutine -def serve(reader, writer): - #print(reader, writer) - #print("================") - yield from reader.read(512) - yield from writer.awrite(resp) - yield from writer.aclose() - #print("Finished processing request") - - -import logging -#logging.basicConfig(level=logging.INFO) -logging.basicConfig(level=logging.DEBUG) -loop = asyncio.get_event_loop(80) -#mem_info() -loop.create_task(asyncio.start_server(serve, "127.0.0.1", 8081, backlog=100)) -loop.run_forever() -loop.close() diff --git a/uasyncio/example_http_client.py b/uasyncio/example_http_client.py deleted file mode 100644 index 1c6cf6876..000000000 --- a/uasyncio/example_http_client.py +++ /dev/null @@ -1,24 +0,0 @@ -import uasyncio as asyncio - -@asyncio.coroutine -def print_http_headers(url): - reader, writer = yield from asyncio.open_connection(url, 80) - print(reader, writer) - print("================") - query = "GET / HTTP/1.0\r\n\r\n" - yield from writer.awrite(query.encode('latin-1')) - while True: - line = yield from reader.readline() - if not line: - break - if line: - print(line.rstrip()) - -import logging -logging.basicConfig(level=logging.INFO) -url = "google.com" -loop = asyncio.get_event_loop() -#task = asyncio.async(print_http_headers(url)) -#loop.run_until_complete(task) -loop.run_until_complete(print_http_headers(url)) -loop.close() diff --git a/uasyncio/example_http_server.py b/uasyncio/example_http_server.py deleted file mode 100644 index 320254748..000000000 --- a/uasyncio/example_http_server.py +++ /dev/null @@ -1,20 +0,0 @@ -import uasyncio as asyncio - -@asyncio.coroutine -def serve(reader, writer): - print(reader, writer) - print("================") - print((yield from reader.read())) - yield from writer.awrite("HTTP/1.0 200 OK\r\n\r\nHello.\r\n") - print("After response write") - yield from writer.aclose() - print("Finished processing request") - - -import logging -#logging.basicConfig(level=logging.INFO) -logging.basicConfig(level=logging.DEBUG) -loop = asyncio.get_event_loop() -loop.call_soon(asyncio.start_server(serve, "127.0.0.1", 8081)) -loop.run_forever() -loop.close() diff --git a/uasyncio/metadata.txt b/uasyncio/metadata.txt deleted file mode 100644 index c0cbd68bf..000000000 --- a/uasyncio/metadata.txt +++ /dev/null @@ -1,7 +0,0 @@ -srctype = micropython-lib -type = package -version = 2.0 -author = Paul Sokolovsky -desc = Lightweight asyncio-like library for MicroPython, built around native Python coroutines. -long_desc = README.rst -depends = uasyncio.core diff --git a/uasyncio/setup.py b/uasyncio/setup.py deleted file mode 100644 index 8bb6fa91b..000000000 --- a/uasyncio/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-uasyncio', - version='2.0', - description='Lightweight asyncio-like library for MicroPython, built around native Python coroutines.', - long_description=open('README.rst').read(), - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['uasyncio'], - install_requires=['micropython-uasyncio.core']) diff --git a/uasyncio/test_echo.py b/uasyncio/test_echo.py deleted file mode 100644 index 5fac7c8b5..000000000 --- a/uasyncio/test_echo.py +++ /dev/null @@ -1,32 +0,0 @@ -from uasyncio import get_event_loop, open_connection, start_server, sleep_ms -from unittest import main, TestCase - -class EchoTestCase(TestCase): - - def test_client_server(self): - '''Simple client-server echo test''' - sockaddr = ('127.0.0.1', 8080) - l = get_event_loop() - - async def echo_server(reader, writer): - data = await reader.readline() - await writer.awrite(data) - await writer.aclose() - - async def echo_client(line, result): - await sleep_ms(10) # Allow server to get up - reader, writer = await open_connection(*sockaddr) - await writer.awrite(line) - data = await reader.readline() - await writer.aclose() - result.append(data) # capture response - - result = [] - l.create_task(start_server(echo_server, *sockaddr)) - l.run_until_complete(echo_client(b'Hello\r\n', result)) - - self.assertEqual(result[0], b'Hello\r\n') - - -if __name__ == '__main__': - main() diff --git a/uasyncio/test_io_starve.py b/uasyncio/test_io_starve.py deleted file mode 100644 index 033eb1fb9..000000000 --- a/uasyncio/test_io_starve.py +++ /dev/null @@ -1,35 +0,0 @@ -try: - import uasyncio as asyncio -except: - import asyncio - -try: - import utime as time -except: - import time - -done = False - -async def receiver(): - global done - with open('test_io_starve.py', 'rb') as f: - sreader = asyncio.StreamReader(f) - while True: - await asyncio.sleep(0.1) - res = await sreader.readline() - # Didn't get there with the original problem this test shows - done = True - - -async def foo(): - start = time.time() - while time.time() - start < 1: - await asyncio.sleep(0) - loop.stop() - -loop = asyncio.get_event_loop() -loop.create_task(foo()) -loop.create_task(receiver()) -loop.run_forever() -assert done -print('OK') diff --git a/uasyncio/test_readexactly.py b/uasyncio/test_readexactly.py deleted file mode 100644 index 59fc53f22..000000000 --- a/uasyncio/test_readexactly.py +++ /dev/null @@ -1,31 +0,0 @@ -from uasyncio import StreamReader - -class MockSock: - - def __init__(self, data_list): - self.data = data_list - - def read(self, sz): - try: - return self.data.pop(0) - except IndexError: - return b"" - - -mock = MockSock([ - b"123", - b"234", b"5", - b"a", b"b", b"c", b"d", b"e", -]) - - -def func(): - sr = StreamReader(mock) - assert await sr.readexactly(3) == b"123" - assert await sr.readexactly(4) == b"2345" - assert await sr.readexactly(5) == b"abcde" - # This isn't how it should be, but the current behavior - assert await sr.readexactly(10) == b"" - -for i in func(): - pass diff --git a/uasyncio/test_readline.py b/uasyncio/test_readline.py deleted file mode 100644 index ac99eaf37..000000000 --- a/uasyncio/test_readline.py +++ /dev/null @@ -1,30 +0,0 @@ -from uasyncio import StreamReader - -class MockSock: - - def __init__(self, data_list): - self.data = data_list - - def readline(self): - try: - return self.data.pop(0) - except IndexError: - return b"" - - -mock = MockSock([ - b"line1\n", - b"parts ", b"of ", b"line2\n", - b"unterminated", -]) - - -def func(): - sr = StreamReader(mock) - assert await sr.readline() == b"line1\n" - assert await sr.readline() == b"parts of line2\n" - assert await sr.readline() == b"unterminated" - assert await sr.readline() == b"" - -for i in func(): - pass diff --git a/uasyncio/uasyncio/__init__.py b/uasyncio/uasyncio/__init__.py deleted file mode 100644 index 41fa57259..000000000 --- a/uasyncio/uasyncio/__init__.py +++ /dev/null @@ -1,258 +0,0 @@ -import uerrno -import uselect as select -import usocket as _socket -from uasyncio.core import * - - -DEBUG = 0 -log = None - -def set_debug(val): - global DEBUG, log - DEBUG = val - if val: - import logging - log = logging.getLogger("uasyncio") - - -class PollEventLoop(EventLoop): - - def __init__(self, runq_len=16, waitq_len=16): - EventLoop.__init__(self, runq_len, waitq_len) - self.poller = select.poll() - self.objmap = {} - - def add_reader(self, sock, cb, *args): - if DEBUG and __debug__: - log.debug("add_reader%s", (sock, cb, args)) - if args: - self.poller.register(sock, select.POLLIN) - self.objmap[id(sock)] = (cb, args) - else: - self.poller.register(sock, select.POLLIN) - self.objmap[id(sock)] = cb - - def remove_reader(self, sock): - if DEBUG and __debug__: - log.debug("remove_reader(%s)", sock) - self.poller.unregister(sock) - del self.objmap[id(sock)] - - def add_writer(self, sock, cb, *args): - if DEBUG and __debug__: - log.debug("add_writer%s", (sock, cb, args)) - if args: - self.poller.register(sock, select.POLLOUT) - self.objmap[id(sock)] = (cb, args) - else: - self.poller.register(sock, select.POLLOUT) - self.objmap[id(sock)] = cb - - def remove_writer(self, sock): - if DEBUG and __debug__: - log.debug("remove_writer(%s)", sock) - try: - self.poller.unregister(sock) - self.objmap.pop(id(sock), None) - except OSError as e: - # StreamWriter.awrite() first tries to write to a socket, - # and if that succeeds, yield IOWrite may never be called - # for that socket, and it will never be added to poller. So, - # ignore such error. - if e.args[0] != uerrno.ENOENT: - raise - - def wait(self, delay): - if DEBUG and __debug__: - log.debug("poll.wait(%d)", delay) - # We need one-shot behavior (second arg of 1 to .poll()) - res = self.poller.ipoll(delay, 1) - #log.debug("poll result: %s", res) - # Remove "if res" workaround after - # https://github.com/micropython/micropython/issues/2716 fixed. - if res: - for sock, ev in res: - cb = self.objmap[id(sock)] - if ev & (select.POLLHUP | select.POLLERR): - # These events are returned even if not requested, and - # are sticky, i.e. will be returned again and again. - # If the caller doesn't do proper error handling and - # unregister this sock, we'll busy-loop on it, so we - # as well can unregister it now "just in case". - self.remove_reader(sock) - if DEBUG and __debug__: - log.debug("Calling IO callback: %r", cb) - if isinstance(cb, tuple): - cb[0](*cb[1]) - else: - cb.pend_throw(None) - self.call_soon(cb) - - -class StreamReader: - - def __init__(self, polls, ios=None): - if ios is None: - ios = polls - self.polls = polls - self.ios = ios - - def read(self, n=-1): - while True: - yield IORead(self.polls) - res = self.ios.read(n) - if res is not None: - break - # This should not happen for real sockets, but can easily - # happen for stream wrappers (ssl, websockets, etc.) - #log.warn("Empty read") - if not res: - yield IOReadDone(self.polls) - return res - - def readexactly(self, n): - buf = b"" - while n: - yield IORead(self.polls) - res = self.ios.read(n) - assert res is not None - if not res: - yield IOReadDone(self.polls) - break - buf += res - n -= len(res) - return buf - - def readline(self): - if DEBUG and __debug__: - log.debug("StreamReader.readline()") - buf = b"" - while True: - yield IORead(self.polls) - res = self.ios.readline() - assert res is not None - if not res: - yield IOReadDone(self.polls) - break - buf += res - if buf[-1] == 0x0a: - break - if DEBUG and __debug__: - log.debug("StreamReader.readline(): %s", buf) - return buf - - def aclose(self): - yield IOReadDone(self.polls) - self.ios.close() - - def __repr__(self): - return "" % (self.polls, self.ios) - - -class StreamWriter: - - def __init__(self, s, extra): - self.s = s - self.extra = extra - - def awrite(self, buf, off=0, sz=-1): - # This method is called awrite (async write) to not proliferate - # incompatibility with original asyncio. Unlike original asyncio - # whose .write() method is both not a coroutine and guaranteed - # to return immediately (which means it has to buffer all the - # data), this method is a coroutine. - if sz == -1: - sz = len(buf) - off - if DEBUG and __debug__: - log.debug("StreamWriter.awrite(): spooling %d bytes", sz) - while True: - res = self.s.write(buf, off, sz) - # If we spooled everything, return immediately - if res == sz: - if DEBUG and __debug__: - log.debug("StreamWriter.awrite(): completed spooling %d bytes", res) - return - if res is None: - res = 0 - if DEBUG and __debug__: - log.debug("StreamWriter.awrite(): spooled partial %d bytes", res) - assert res < sz - off += res - sz -= res - yield IOWrite(self.s) - #assert s2.fileno() == self.s.fileno() - if DEBUG and __debug__: - log.debug("StreamWriter.awrite(): can write more") - - # Write piecewise content from iterable (usually, a generator) - def awriteiter(self, iterable): - for buf in iterable: - yield from self.awrite(buf) - - def aclose(self): - yield IOWriteDone(self.s) - self.s.close() - - def get_extra_info(self, name, default=None): - return self.extra.get(name, default) - - def __repr__(self): - return "" % self.s - - -def open_connection(host, port, ssl=False): - if DEBUG and __debug__: - log.debug("open_connection(%s, %s)", host, port) - ai = _socket.getaddrinfo(host, port, 0, _socket.SOCK_STREAM) - ai = ai[0] - s = _socket.socket(ai[0], ai[1], ai[2]) - s.setblocking(False) - try: - s.connect(ai[-1]) - except OSError as e: - if e.args[0] != uerrno.EINPROGRESS: - raise - if DEBUG and __debug__: - log.debug("open_connection: After connect") - yield IOWrite(s) -# if __debug__: -# assert s2.fileno() == s.fileno() - if DEBUG and __debug__: - log.debug("open_connection: After iowait: %s", s) - if ssl: - print("Warning: uasyncio SSL support is alpha") - import ussl - s.setblocking(True) - s2 = ussl.wrap_socket(s) - s.setblocking(False) - return StreamReader(s, s2), StreamWriter(s2, {}) - return StreamReader(s), StreamWriter(s, {}) - - -def start_server(client_coro, host, port, backlog=10): - if DEBUG and __debug__: - log.debug("start_server(%s, %s)", host, port) - ai = _socket.getaddrinfo(host, port, 0, _socket.SOCK_STREAM) - ai = ai[0] - s = _socket.socket(ai[0], ai[1], ai[2]) - s.setblocking(False) - - s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1) - s.bind(ai[-1]) - s.listen(backlog) - while True: - if DEBUG and __debug__: - log.debug("start_server: Before accept") - yield IORead(s) - if DEBUG and __debug__: - log.debug("start_server: After iowait") - s2, client_addr = s.accept() - s2.setblocking(False) - if DEBUG and __debug__: - log.debug("start_server: After accept: %s", s2) - extra = {"peername": client_addr} - yield client_coro(StreamReader(s2), StreamWriter(s2, extra)) - - -import uasyncio.core -uasyncio.core._event_loop_class = PollEventLoop diff --git a/ucontextlib/setup.py b/ucontextlib/setup.py deleted file mode 100644 index 1cc5587b2..000000000 --- a/ucontextlib/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-ucontextlib', - version='0.1.1', - description='ucontextlib module for MicroPython', - long_description='Minimal subset of contextlib for MicroPython low-memory ports', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['ucontextlib']) diff --git a/ucurses/setup.py b/ucurses/setup.py deleted file mode 100644 index c4c74d2f2..000000000 --- a/ucurses/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-ucurses', - version='0.1.2', - description='ucurses module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['ucurses'], - install_requires=['micropython-os', 'micropython-tty', 'micropython-select']) diff --git a/udnspkt/setup.py b/udnspkt/setup.py deleted file mode 100644 index 9f95ea004..000000000 --- a/udnspkt/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-udnspkt', - version='0.1', - description='Make and parse DNS packets (Sans I/O approach).', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['udnspkt']) diff --git a/umqtt.robust/setup.py b/umqtt.robust/setup.py deleted file mode 100644 index e6f5d9b7f..000000000 --- a/umqtt.robust/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-umqtt.robust', - version='1.0.1', - description='Lightweight MQTT client for MicroPython ("robust" version).', - long_description=open('README.rst').read(), - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['umqtt']) diff --git a/umqtt.simple/setup.py b/umqtt.simple/setup.py deleted file mode 100644 index 0d77c9466..000000000 --- a/umqtt.simple/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-umqtt.simple', - version='1.3.4', - description='Lightweight MQTT client for MicroPython.', - long_description=open('README.rst').read(), - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['umqtt']) diff --git a/unicodedata/metadata.txt b/unicodedata/metadata.txt deleted file mode 100644 index 849688fb8..000000000 --- a/unicodedata/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.3 diff --git a/unicodedata/setup.py b/unicodedata/setup.py deleted file mode 100644 index 4635da4dc..000000000 --- a/unicodedata/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-unicodedata', - version='0.0.3', - description='Dummy unicodedata module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['unicodedata']) diff --git a/unicodedata/unicodedata.py b/unicodedata/unicodedata.py deleted file mode 100644 index 2b6cfd7e1..000000000 --- a/unicodedata/unicodedata.py +++ /dev/null @@ -1,6 +0,0 @@ -def east_asian_width(c): - return 1 - - -def normalize(form, unistr): - return unistr diff --git a/unittest/setup.py b/unittest/setup.py deleted file mode 100644 index 2b9990eb6..000000000 --- a/unittest/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-unittest', - version='0.3.2', - description='unittest module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['unittest']) diff --git a/unix-ffi/README.md b/unix-ffi/README.md new file mode 100644 index 000000000..ae58362c8 --- /dev/null +++ b/unix-ffi/README.md @@ -0,0 +1,17 @@ +Unix-specific libraries +======================= + +These are libraries that will only run on the Unix port of MicroPython. There is some limited support for the Windows port too. + +**Note:** This directory is largely unmaintained, although large breaking changes are not expected. + +Background +---------- + +The libraries in this directory provide additional CPython compatibility using +the host operating system's native libraries. + +This is implemented either by accessing the libraries directly via libffi, or by using built-in modules that are only available on the Unix port. + +In theory, this allows you to use MicroPython as a more complete drop-in +replacement for CPython. diff --git a/_libc/_libc.py b/unix-ffi/_libc/_libc.py similarity index 89% rename from _libc/_libc.py rename to unix-ffi/_libc/_libc.py index a930cbf71..839b9d544 100644 --- a/_libc/_libc.py +++ b/unix-ffi/_libc/_libc.py @@ -4,7 +4,8 @@ _h = None -names = ('libc.so', 'libc.so.0', 'libc.so.6', 'libc.dylib') +names = ("libc.so", "libc.so.0", "libc.so.6", "libc.dylib") + def get(): global _h @@ -24,6 +25,7 @@ def set_names(n): global names names = n + # Find out bitness of the platform, even if long ints are not supported # TODO: All bitness differences should be removed from micropython-lib, and # this snippet too. diff --git a/_libc/metadata.txt b/unix-ffi/_libc/metadata.txt similarity index 100% rename from _libc/metadata.txt rename to unix-ffi/_libc/metadata.txt diff --git a/unix-ffi/_libc/setup.py b/unix-ffi/_libc/setup.py new file mode 100644 index 000000000..a2530cc5b --- /dev/null +++ b/unix-ffi/_libc/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-libc", + version="0.3.1", + description="MicroPython FFI helper module (deprecated)", + long_description="MicroPython FFI helper module (deprecated, replaced by micropython-ffilib).", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["_libc"], +) diff --git a/datetime/datetime.py b/unix-ffi/datetime/datetime.py similarity index 83% rename from datetime/datetime.py rename to unix-ffi/datetime/datetime.py index 03b4e4cdd..dd50b3cfa 100644 --- a/datetime/datetime.py +++ b/unix-ffi/datetime/datetime.py @@ -7,12 +7,14 @@ import time as _time import math as _math + def _cmp(x, y): return 0 if x == y else 1 if x > y else -1 + MINYEAR = 1 MAXYEAR = 9999 -_MAXORDINAL = 3652059 # date.max.toordinal() +_MAXORDINAL = 3652059 # date.max.toordinal() # Utility functions, adapted from Python's Demo/classes/Dates.py, which # also assumes the current Gregorian calendar indefinitely extended in @@ -32,14 +34,17 @@ def _cmp(x, y): dbm += dim del dbm, dim + def _is_leap(year): "year -> 1 if leap year, else 0." return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) + def _days_before_year(year): "year -> number of days before January 1st of year." y = year - 1 - return y*365 + y//4 - y//100 + y//400 + return y * 365 + y // 4 - y // 100 + y // 400 + def _days_in_month(year, month): "year, month -> number of days in that month in that year." @@ -48,23 +53,24 @@ def _days_in_month(year, month): return 29 return _DAYS_IN_MONTH[month] + def _days_before_month(year, month): "year, month -> number of days in year preceding first day of month." - assert 1 <= month <= 12, 'month must be in 1..12' + assert 1 <= month <= 12, "month must be in 1..12" return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year)) + def _ymd2ord(year, month, day): "year, month, day -> ordinal, considering 01-Jan-0001 as day 1." - assert 1 <= month <= 12, 'month must be in 1..12' + assert 1 <= month <= 12, "month must be in 1..12" dim = _days_in_month(year, month) - assert 1 <= day <= dim, ('day must be in 1..%d' % dim) - return (_days_before_year(year) + - _days_before_month(year, month) + - day) + assert 1 <= day <= dim, "day must be in 1..%d" % dim + return _days_before_year(year) + _days_before_month(year, month) + day + -_DI400Y = _days_before_year(401) # number of days in 400 years -_DI100Y = _days_before_year(101) # " " " " 100 " -_DI4Y = _days_before_year(5) # " " " " 4 " +_DI400Y = _days_before_year(401) # number of days in 400 years +_DI100Y = _days_before_year(101) # " " " " 100 " +_DI4Y = _days_before_year(5) # " " " " 4 " # A 4-year cycle has an extra leap day over what we'd get from pasting # together 4 single years. @@ -78,6 +84,7 @@ def _ymd2ord(year, month, day): # pasting together 25 4-year cycles. assert _DI100Y == 25 * _DI4Y - 1 + def _ord2ymd(n): "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1." @@ -103,7 +110,7 @@ def _ord2ymd(n): # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary n -= 1 n400, n = divmod(n, _DI400Y) - year = n400 * 400 + 1 # ..., -399, 1, 401, ... + year = n400 * 400 + 1 # ..., -399, 1, 401, ... # Now n is the (non-negative) offset, in days, from January 1 of year, to # the desired date. Now compute how many 100-year cycles precede n. @@ -122,7 +129,7 @@ def _ord2ymd(n): year += n100 * 100 + n4 * 4 + n1 if n1 == 4 or n100 == 4: assert n == 0 - return year-1, 12, 31 + return year - 1, 12, 31 # Now the year is correct, and n is the offset from January 1. We find # the month via an estimate that's either exact or one too large. @@ -138,11 +145,25 @@ def _ord2ymd(n): # Now the year and month are correct, and n is the offset from the # start of that month: we're done! - return year, month, n+1 + return year, month, n + 1 + # Month and day names. For localized versions, see the calendar module. -_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] +_MONTHNAMES = [ + None, + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", +] _DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] @@ -151,6 +172,7 @@ def _build_struct_time(y, m, d, hh, mm, ss, dstflag): dnum = _days_before_month(y, m) + d return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag)) + def _format_time(hh, mm, ss, us): # Skip trailing microseconds when us==0. result = "%02d:%02d:%02d" % (hh, mm, ss) @@ -158,12 +180,13 @@ def _format_time(hh, mm, ss, us): result += ".%06d" % us return result + # Correctly substitute for %z and %Z escapes in strftime formats. def _wrap_strftime(object, format, timetuple): # Don't call utcoffset() or tzname() unless actually needed. - freplace = None # the string to use for %f - zreplace = None # the string to use for %z - Zreplace = None # the string to use for %Z + freplace = None # the string to use for %f + zreplace = None # the string to use for %z + Zreplace = None # the string to use for %Z # Scan format for %z and %Z escapes, replacing as needed. newformat = [] @@ -172,60 +195,61 @@ def _wrap_strftime(object, format, timetuple): while i < n: ch = format[i] i += 1 - if ch == '%': + if ch == "%": if i < n: ch = format[i] i += 1 - if ch == 'f': + if ch == "f": if freplace is None: - freplace = '%06d' % getattr(object, - 'microsecond', 0) + freplace = "%06d" % getattr(object, "microsecond", 0) newformat.append(freplace) - elif ch == 'z': + elif ch == "z": if zreplace is None: zreplace = "" if hasattr(object, "utcoffset"): offset = object.utcoffset() if offset is not None: - sign = '+' + sign = "+" if offset.days < 0: offset = -offset - sign = '-' + sign = "-" h, m = divmod(offset, timedelta(hours=1)) assert not m % timedelta(minutes=1), "whole minute" m //= timedelta(minutes=1) - zreplace = '%c%02d%02d' % (sign, h, m) - assert '%' not in zreplace + zreplace = "%c%02d%02d" % (sign, h, m) + assert "%" not in zreplace newformat.append(zreplace) - elif ch == 'Z': + elif ch == "Z": if Zreplace is None: Zreplace = "" if hasattr(object, "tzname"): s = object.tzname() if s is not None: # strftime is going to have at this: escape % - Zreplace = s.replace('%', '%%') + Zreplace = s.replace("%", "%%") newformat.append(Zreplace) else: - push('%') + push("%") push(ch) else: - push('%') + push("%") else: push(ch) newformat = "".join(newformat) return _time.strftime(newformat, timetuple) + def _call_tzinfo_method(tzinfo, methname, tzinfoarg): if tzinfo is None: return None return getattr(tzinfo, methname)(tzinfoarg) + # Just raise TypeError if the arg isn't None or a string. def _check_tzname(name): if name is not None and not isinstance(name, str): - raise TypeError("tzinfo.tzname() must return None or string, " - "not '%s'" % type(name)) + raise TypeError("tzinfo.tzname() must return None or string, " "not '%s'" % type(name)) + # name is the offset-producing method, "utcoffset" or "dst". # offset is what it returned. @@ -238,46 +262,53 @@ def _check_utc_offset(name, offset): if offset is None: return if not isinstance(offset, timedelta): - raise TypeError("tzinfo.%s() must return None " - "or timedelta, not '%s'" % (name, type(offset))) + raise TypeError( + "tzinfo.%s() must return None " "or timedelta, not '%s'" % (name, type(offset)) + ) if offset % timedelta(minutes=1) or offset.microseconds: - raise ValueError("tzinfo.%s() must return a whole number " - "of minutes, got %s" % (name, offset)) + raise ValueError( + "tzinfo.%s() must return a whole number " "of minutes, got %s" % (name, offset) + ) if not -timedelta(1) < offset < timedelta(1): - raise ValueError("%s()=%s, must be must be strictly between" - " -timedelta(hours=24) and timedelta(hours=24)" - % (name, offset)) + raise ValueError( + "%s()=%s, must be must be strictly between" + " -timedelta(hours=24) and timedelta(hours=24)" % (name, offset) + ) + def _check_date_fields(year, month, day): if not isinstance(year, int): - raise TypeError('int expected') + raise TypeError("int expected") if not MINYEAR <= year <= MAXYEAR: - raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year) + raise ValueError("year must be in %d..%d" % (MINYEAR, MAXYEAR), year) if not 1 <= month <= 12: - raise ValueError('month must be in 1..12', month) + raise ValueError("month must be in 1..12", month) dim = _days_in_month(year, month) if not 1 <= day <= dim: - raise ValueError('day must be in 1..%d' % dim, day) + raise ValueError("day must be in 1..%d" % dim, day) + def _check_time_fields(hour, minute, second, microsecond): if not isinstance(hour, int): - raise TypeError('int expected') + raise TypeError("int expected") if not 0 <= hour <= 23: - raise ValueError('hour must be in 0..23', hour) + raise ValueError("hour must be in 0..23", hour) if not 0 <= minute <= 59: - raise ValueError('minute must be in 0..59', minute) + raise ValueError("minute must be in 0..59", minute) if not 0 <= second <= 59: - raise ValueError('second must be in 0..59', second) + raise ValueError("second must be in 0..59", second) if not 0 <= microsecond <= 999999: - raise ValueError('microsecond must be in 0..999999', microsecond) + raise ValueError("microsecond must be in 0..999999", microsecond) + def _check_tzinfo_arg(tz): if tz is not None and not isinstance(tz, tzinfo): raise TypeError("tzinfo argument must be None or of a tzinfo subclass") + def _cmperror(x, y): - raise TypeError("can't compare '%s' to '%s'" % ( - type(x).__name__, type(y).__name__)) + raise TypeError("can't compare '%s' to '%s'" % (type(x).__name__, type(y).__name__)) + class timedelta: """Represent the difference between two datetime objects. @@ -296,10 +327,12 @@ class timedelta: Representation: (days, seconds, microseconds). Why? Because I felt like it. """ - __slots__ = '_days', '_seconds', '_microseconds' - def __new__(cls, days=0, seconds=0, microseconds=0, - milliseconds=0, minutes=0, hours=0, weeks=0): + __slots__ = "_days", "_seconds", "_microseconds" + + def __new__( + cls, days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0 + ): # Doing this efficiently and accurately in C is going to be difficult # and error-prone, due to ubiquitous overflow possibilities, and that # C double doesn't have enough bits of precision to represent @@ -315,15 +348,15 @@ def __new__(cls, days=0, seconds=0, microseconds=0, d = s = us = 0 # Normalize everything to days, seconds, microseconds. - days += weeks*7 - seconds += minutes*60 + hours*3600 - microseconds += milliseconds*1000 + days += weeks * 7 + seconds += minutes * 60 + hours * 3600 + microseconds += milliseconds * 1000 # Get rid of all fractions, and normalize s and us. # Take a deep breath . if isinstance(days, float): dayfrac, days = _math.modf(days) - daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.)) + daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.0 * 3600.0)) assert daysecondswhole == int(daysecondswhole) # can't overflow s = int(daysecondswhole) assert days == int(days) @@ -350,15 +383,15 @@ def __new__(cls, days=0, seconds=0, microseconds=0, assert abs(secondsfrac) <= 2.0 assert isinstance(seconds, int) - days, seconds = divmod(seconds, 24*3600) + days, seconds = divmod(seconds, 24 * 3600) d += days - s += int(seconds) # can't overflow + s += int(seconds) # can't overflow assert isinstance(s, int) assert abs(s) <= 2 * 24 * 3600 # seconds isn't referenced again before redefinition usdouble = secondsfrac * 1e6 - assert abs(usdouble) < 2.1e6 # exact value not critical + assert abs(usdouble) < 2.1e6 # exact value not critical # secondsfrac isn't referenced again if isinstance(microseconds, float): @@ -367,18 +400,18 @@ def __new__(cls, days=0, seconds=0, microseconds=0, seconds, microseconds = divmod(microseconds, 1e6) assert microseconds == int(microseconds) assert seconds == int(seconds) - days, seconds = divmod(seconds, 24.*3600.) + days, seconds = divmod(seconds, 24.0 * 3600.0) assert days == int(days) assert seconds == int(seconds) d += int(days) - s += int(seconds) # can't overflow + s += int(seconds) # can't overflow assert isinstance(s, int) assert abs(s) <= 3 * 24 * 3600 else: seconds, microseconds = divmod(microseconds, 1000000) - days, seconds = divmod(seconds, 24*3600) + days, seconds = divmod(seconds, 24 * 3600) d += days - s += int(seconds) # can't overflow + s += int(seconds) # can't overflow assert isinstance(s, int) assert abs(s) <= 3 * 24 * 3600 microseconds = float(microseconds) @@ -392,13 +425,13 @@ def __new__(cls, days=0, seconds=0, microseconds=0, assert int(microseconds) == microseconds us = int(microseconds) seconds, us = divmod(us, 1000000) - s += seconds # cant't overflow + s += seconds # cant't overflow assert isinstance(s, int) - days, s = divmod(s, 24*3600) + days, s = divmod(s, 24 * 3600) d += days assert isinstance(d, int) - assert isinstance(s, int) and 0 <= s < 24*3600 + assert isinstance(s, int) and 0 <= s < 24 * 3600 assert isinstance(us, int) and 0 <= us < 1000000 self = object.__new__(cls) @@ -413,23 +446,29 @@ def __new__(cls, days=0, seconds=0, microseconds=0, def __repr__(self): if self._microseconds: - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__, - self._days, - self._seconds, - self._microseconds) + return "%s(%d, %d, %d)" % ( + "datetime." + self.__class__.__name__, + self._days, + self._seconds, + self._microseconds, + ) if self._seconds: - return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__, - self._days, - self._seconds) - return "%s(%d)" % ('datetime.' + self.__class__.__name__, self._days) + return "%s(%d, %d)" % ( + "datetime." + self.__class__.__name__, + self._days, + self._seconds, + ) + return "%s(%d)" % ("datetime." + self.__class__.__name__, self._days) def __str__(self): mm, ss = divmod(self._seconds, 60) hh, mm = divmod(mm, 60) s = "%d:%02d:%02d" % (hh, mm, ss) if self._days: + def plural(n): return n, abs(n) != 1 and "s" or "" + s = ("%d day%s, " % plural(self._days)) + s if self._microseconds: s = s + ".%06d" % self._microseconds @@ -437,8 +476,7 @@ def plural(n): def total_seconds(self): """Total seconds in the duration.""" - return ((self.days * 86400 + self.seconds)*10**6 + - self.microseconds) / 10**6 + return ((self.days * 86400 + self.seconds) * 10 ** 6 + self.microseconds) / 10 ** 6 # Read-only field accessors @property @@ -460,9 +498,11 @@ def __add__(self, other): if isinstance(other, timedelta): # for CPython compatibility, we cannot use # our __class__ here, but need a real timedelta - return timedelta(self._days + other._days, - self._seconds + other._seconds, - self._microseconds + other._microseconds) + return timedelta( + self._days + other._days, + self._seconds + other._seconds, + self._microseconds + other._microseconds, + ) return NotImplemented __radd__ = __add__ @@ -471,9 +511,11 @@ def __sub__(self, other): if isinstance(other, timedelta): # for CPython compatibility, we cannot use # our __class__ here, but need a real timedelta - return timedelta(self._days - other._days, - self._seconds - other._seconds, - self._microseconds - other._microseconds) + return timedelta( + self._days - other._days, + self._seconds - other._seconds, + self._microseconds - other._microseconds, + ) return NotImplemented def __rsub__(self, other): @@ -484,9 +526,7 @@ def __rsub__(self, other): def __neg__(self): # for CPython compatibility, we cannot use # our __class__ here, but need a real timedelta - return timedelta(-self._days, - -self._seconds, - -self._microseconds) + return timedelta(-self._days, -self._seconds, -self._microseconds) def __pos__(self): return self @@ -501,12 +541,10 @@ def __mul__(self, other): if isinstance(other, int): # for CPython compatibility, we cannot use # our __class__ here, but need a real timedelta - return timedelta(self._days * other, - self._seconds * other, - self._microseconds * other) + return timedelta(self._days * other, self._seconds * other, self._microseconds * other) if isinstance(other, float): - #a, b = other.as_integer_ratio() - #return self * a / b + # a, b = other.as_integer_ratio() + # return self * a / b usec = self._to_microseconds() return timedelta(0, 0, round(usec * other)) return NotImplemented @@ -514,8 +552,7 @@ def __mul__(self, other): __rmul__ = __mul__ def _to_microseconds(self): - return ((self._days * (24*3600) + self._seconds) * 1000000 + - self._microseconds) + return (self._days * (24 * 3600) + self._seconds) * 1000000 + self._microseconds def __floordiv__(self, other): if not isinstance(other, (int, timedelta)): @@ -535,8 +572,8 @@ def __truediv__(self, other): if isinstance(other, int): return timedelta(0, 0, usec / other) if isinstance(other, float): -# a, b = other.as_integer_ratio() -# return timedelta(0, 0, b * usec / a) + # a, b = other.as_integer_ratio() + # return timedelta(0, 0, b * usec / a) return timedelta(0, 0, round(usec / other)) def __mod__(self, other): @@ -547,8 +584,7 @@ def __mod__(self, other): def __divmod__(self, other): if isinstance(other, timedelta): - q, r = divmod(self._to_microseconds(), - other._to_microseconds()) + q, r = divmod(self._to_microseconds(), other._to_microseconds()) return q, timedelta(0, 0, r) return NotImplemented @@ -598,9 +634,7 @@ def __hash__(self): return hash(self._getstate()) def __bool__(self): - return (self._days != 0 or - self._seconds != 0 or - self._microseconds != 0) + return self._days != 0 or self._seconds != 0 or self._microseconds != 0 # Pickle support. @@ -610,11 +644,12 @@ def _getstate(self): def __reduce__(self): return (self.__class__, self._getstate()) + timedelta.min = timedelta(-999999999) -timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59, - microseconds=999999) +timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999) timedelta.resolution = timedelta(microseconds=1) + class date: """Concrete date type. @@ -643,7 +678,8 @@ class date: Properties (readonly): year, month, day """ - __slots__ = '_year', '_month', '_day' + + __slots__ = "_year", "_month", "_day" def __new__(cls, year, month=None, day=None): """Constructor. @@ -652,8 +688,9 @@ def __new__(cls, year, month=None, day=None): year, month, day (required, base 1) """ - if (isinstance(year, bytes) and len(year) == 4 and - 1 <= year[2] <= 12 and month is None): # Month is sane + if ( + isinstance(year, bytes) and len(year) == 4 and 1 <= year[2] <= 12 and month is None + ): # Month is sane # Pickle support self = object.__new__(cls) self.__setstate(year) @@ -702,23 +739,27 @@ def __repr__(self): >>> repr(dt) 'datetime.datetime(2010, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)' """ - return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__, - self._year, - self._month, - self._day) + return "%s(%d, %d, %d)" % ( + "datetime." + self.__class__.__name__, + self._year, + self._month, + self._day, + ) + # XXX These shouldn't depend on time.localtime(), because that # clips the usable dates to [1970 .. 2038). At least ctime() is # easily done without using strftime() -- that's better too because # strftime("%c", ...) is locale specific. - def ctime(self): "Return ctime() style string." weekday = self.toordinal() % 7 or 7 return "%s %s %2d 00:00:00 %04d" % ( _DAYNAMES[weekday], _MONTHNAMES[self._month], - self._day, self._year) + self._day, + self._year, + ) def strftime(self, fmt): "Format using strftime()." @@ -762,8 +803,7 @@ def day(self): def timetuple(self): "Return local time tuple compatible with time.localtime()." - return _build_struct_time(self._year, self._month, self._day, - 0, 0, 0, -1) + return _build_struct_time(self._year, self._month, self._day, 0, 0, 0, -1) def toordinal(self): """Return proleptic Gregorian ordinal for the year, month and day. @@ -882,16 +922,16 @@ def isocalendar(self): week1monday = _isoweek1monday(year) week, day = divmod(today - week1monday, 7) elif week >= 52: - if today >= _isoweek1monday(year+1): + if today >= _isoweek1monday(year + 1): year += 1 week = 0 - return year, week+1, day+1 + return year, week + 1, day + 1 # Pickle support. def _getstate(self): yhi, ylo = divmod(self._year, 256) - return bytes([yhi, ylo, self._month, self._day]), + return (bytes([yhi, ylo, self._month, self._day]),) def __setstate(self, string): if len(string) != 4 or not (1 <= string[2] <= 12): @@ -902,18 +942,22 @@ def __setstate(self, string): def __reduce__(self): return (self.__class__, self._getstate()) + _date_class = date # so functions w/ args named "date" can get at the class date.min = date(1, 1, 1) date.max = date(9999, 12, 31) date.resolution = timedelta(days=1) + class tzinfo: """Abstract base class for time zone info classes. Subclasses must override the name(), utcoffset() and dst() methods. """ + __slots__ = () + def tzname(self, dt): "datetime -> string name of time zone." raise NotImplementedError("tzinfo subclass must override tzname()") @@ -940,8 +984,7 @@ def fromutc(self, dt): dtoff = dt.utcoffset() if dtoff is None: - raise ValueError("fromutc() requires a non-None utcoffset() " - "result") + raise ValueError("fromutc() requires a non-None utcoffset() " "result") # See the long comment block at the end of this file for an # explanation of this algorithm. @@ -953,8 +996,7 @@ def fromutc(self, dt): dt += delta dtdst = dt.dst() if dtdst is None: - raise ValueError("fromutc(): dt.dst gave inconsistent " - "results; cannot convert") + raise ValueError("fromutc(): dt.dst gave inconsistent " "results; cannot convert") return dt + dtdst # Pickle support. @@ -975,8 +1017,10 @@ def __reduce__(self): else: return (self.__class__, args, state) + _tzinfo_class = tzinfo + class time: """Time with time zone. @@ -1104,27 +1148,27 @@ def _cmp(self, other, allow_mixed=False): base_compare = myoff == otoff if base_compare: - return _cmp((self._hour, self._minute, self._second, - self._microsecond), - (other._hour, other._minute, other._second, - other._microsecond)) + return _cmp( + (self._hour, self._minute, self._second, self._microsecond), + (other._hour, other._minute, other._second, other._microsecond), + ) if myoff is None or otoff is None: if allow_mixed: - return 2 # arbitrary non-zero value + return 2 # arbitrary non-zero value else: raise TypeError("cannot compare naive and aware times") - myhhmm = self._hour * 60 + self._minute - myoff//timedelta(minutes=1) - othhmm = other._hour * 60 + other._minute - otoff//timedelta(minutes=1) - return _cmp((myhhmm, self._second, self._microsecond), - (othhmm, other._second, other._microsecond)) + myhhmm = self._hour * 60 + self._minute - myoff // timedelta(minutes=1) + othhmm = other._hour * 60 + other._minute - otoff // timedelta(minutes=1) + return _cmp( + (myhhmm, self._second, self._microsecond), (othhmm, other._second, other._microsecond) + ) def __hash__(self): """Hash.""" tzoff = self.utcoffset() - if not tzoff: # zero or None + if not tzoff: # zero or None return hash(self._getstate()[0]) - h, m = divmod(timedelta(hours=self.hour, minutes=self.minute) - tzoff, - timedelta(hours=1)) + h, m = divmod(timedelta(hours=self.hour, minutes=self.minute) - tzoff, timedelta(hours=1)) assert not m % timedelta(minutes=1), "whole minute" m //= timedelta(minutes=1) if 0 <= h < 24: @@ -1157,8 +1201,7 @@ def __repr__(self): s = ", %d" % self._second else: s = "" - s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__, - self._hour, self._minute, s) + s = "%s(%d, %d%s)" % ("datetime." + self.__class__.__name__, self._hour, self._minute, s) if self._tzinfo is not None: assert s[-1:] == ")" s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")" @@ -1170,8 +1213,7 @@ def isoformat(self): This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if self.microsecond == 0. """ - s = _format_time(self._hour, self._minute, self._second, - self._microsecond) + s = _format_time(self._hour, self._minute, self._second, self._microsecond) tz = self._tzstr() if tz: s += tz @@ -1185,9 +1227,7 @@ def strftime(self, fmt): """ # The year must be >= 1000 else Python's strftime implementation # can raise a bogus exception. - timetuple = (1900, 1, 1, - self._hour, self._minute, self._second, - 0, 1, -1) + timetuple = (1900, 1, 1, self._hour, self._minute, self._second, 0, 1, -1) return _wrap_strftime(self, fmt, timetuple) def __format__(self, fmt): @@ -1234,8 +1274,7 @@ def dst(self): _check_utc_offset("dst", offset) return offset - def replace(self, hour=None, minute=None, second=None, microsecond=None, - tzinfo=True): + def replace(self, hour=None, minute=None, second=None, microsecond=None, tzinfo=True): """Return a new time with new values for the specified fields.""" if hour is None: hour = self.hour @@ -1262,8 +1301,7 @@ def __bool__(self): def _getstate(self): us2, us3 = divmod(self._microsecond, 256) us1, us2 = divmod(us2, 256) - basestate = bytes([self._hour, self._minute, self._second, - us1, us2, us3]) + basestate = bytes([self._hour, self._minute, self._second, us1, us2, us3]) if self._tzinfo is None: return (basestate,) else: @@ -1272,8 +1310,7 @@ def _getstate(self): def __setstate(self, string, tzinfo): if len(string) != 6 or string[0] >= 24: raise TypeError("an integer is required") - (self._hour, self._minute, self._second, - us1, us2, us3) = string + (self._hour, self._minute, self._second, us1, us2, us3) = string self._microsecond = (((us1 << 8) | us2) << 8) | us3 if tzinfo is None or isinstance(tzinfo, _tzinfo_class): self._tzinfo = tzinfo @@ -1283,12 +1320,14 @@ def __setstate(self, string, tzinfo): def __reduce__(self): return (time, self._getstate()) + _time_class = time # so functions w/ args named "time" can get at the class time.min = time(0, 0, 0) time.max = time(23, 59, 59, 999999) time.resolution = timedelta(microseconds=1) + class datetime(date): """datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) @@ -1296,11 +1335,11 @@ class datetime(date): instance of a tzinfo subclass. The remaining arguments may be ints. """ - __slots__ = date.__slots__ + ( - '_hour', '_minute', '_second', - '_microsecond', '_tzinfo') - def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0, - microsecond=0, tzinfo=None): + __slots__ = date.__slots__ + ("_hour", "_minute", "_second", "_microsecond", "_tzinfo") + + def __new__( + cls, year, month=None, day=None, hour=0, minute=0, second=0, microsecond=0, tzinfo=None + ): if isinstance(year, bytes) and len(year) == 10: # Pickle support self = date.__new__(cls, year[:4]) @@ -1364,7 +1403,7 @@ def fromtimestamp(cls, t, tz=None): t += 1 us = 0 y, m, d, hh, mm, ss, weekday, jday, dst = converter(t) - ss = min(ss, 59) # clamp out leap seconds if the platform has them + ss = min(ss, 59) # clamp out leap seconds if the platform has them result = cls(y, m, d, hh, mm, ss, us, tz) if tz is not None: result = tz.fromutc(result) @@ -1384,7 +1423,7 @@ def utcfromtimestamp(cls, t): t += 1 us = 0 y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t) - ss = min(ss, 59) # clamp out leap seconds if the platform has them + ss = min(ss, 59) # clamp out leap seconds if the platform has them return cls(y, m, d, hh, mm, ss, us) # XXX This is supposed to do better than we *can* do by using time.time(), @@ -1411,9 +1450,16 @@ def combine(cls, date, time): raise TypeError("date argument must be a date instance") if not isinstance(time, _time_class): raise TypeError("time argument must be a time instance") - return cls(date.year, date.month, date.day, - time.hour, time.minute, time.second, time.microsecond, - time.tzinfo) + return cls( + date.year, + date.month, + date.day, + time.hour, + time.minute, + time.second, + time.microsecond, + time.tzinfo, + ) def timetuple(self): "Return local time tuple compatible with time.localtime()." @@ -1424,16 +1470,29 @@ def timetuple(self): dst = 1 else: dst = 0 - return _build_struct_time(self.year, self.month, self.day, - self.hour, self.minute, self.second, - dst) + return _build_struct_time( + self.year, self.month, self.day, self.hour, self.minute, self.second, dst + ) def timestamp(self): "Return POSIX timestamp as float" if self._tzinfo is None: - return _time.mktime((self.year, self.month, self.day, - self.hour, self.minute, self.second, - -1, -1, -1)) + self.microsecond / 1e6 + return ( + _time.mktime( + ( + self.year, + self.month, + self.day, + self.hour, + self.minute, + self.second, + -1, + -1, + -1, + ) + ) + + self.microsecond / 1e6 + ) else: return (self - _EPOCH).total_seconds() @@ -1456,11 +1515,19 @@ def time(self): def timetz(self): "Return the time part, with same tzinfo." - return time(self.hour, self.minute, self.second, self.microsecond, - self._tzinfo) - - def replace(self, year=None, month=None, day=None, hour=None, - minute=None, second=None, microsecond=None, tzinfo=True): + return time(self.hour, self.minute, self.second, self.microsecond, self._tzinfo) + + def replace( + self, + year=None, + month=None, + day=None, + hour=None, + minute=None, + second=None, + microsecond=None, + tzinfo=True, + ): """Return a new datetime with new values for the specified fields.""" if year is None: year = self.year @@ -1481,8 +1548,7 @@ def replace(self, year=None, month=None, day=None, hour=None, _check_date_fields(year, month, day) _check_time_fields(hour, minute, second, microsecond) _check_tzinfo_arg(tzinfo) - return datetime(year, month, day, hour, minute, second, - microsecond, tzinfo) + return datetime(year, month, day, hour, minute, second, microsecond, tzinfo) def astimezone(self, tz=None): if tz is None: @@ -1537,10 +1603,13 @@ def ctime(self): _DAYNAMES[weekday], _MONTHNAMES[self._month], self._day, - self._hour, self._minute, self._second, - self._year) + self._hour, + self._minute, + self._second, + self._year, + ) - def isoformat(self, sep='T'): + def isoformat(self, sep="T"): """Return the time formatted according to ISO. This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if @@ -1552,10 +1621,9 @@ def isoformat(self, sep='T'): Optional argument sep specifies the separator between date and time, default 'T'. """ - s = ("%04d-%02d-%02d%s" % (self._year, self._month, self._day, - sep) + - _format_time(self._hour, self._minute, self._second, - self._microsecond)) + s = "%04d-%02d-%02d%s" % (self._year, self._month, self._day, sep) + _format_time( + self._hour, self._minute, self._second, self._microsecond + ) off = self.utcoffset() if off is not None: if off.days < 0: @@ -1571,14 +1639,21 @@ def isoformat(self, sep='T'): def __repr__(self): """Convert to formal string, for repr().""" - L = [self._year, self._month, self._day, # These are never zero - self._hour, self._minute, self._second, self._microsecond] + L = [ + self._year, + self._month, + self._day, # These are never zero + self._hour, + self._minute, + self._second, + self._microsecond, + ] if L[-1] == 0: del L[-1] if L[-1] == 0: del L[-1] s = ", ".join(map(str, L)) - s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s) + s = "%s(%s)" % ("datetime." + self.__class__.__name__, s) if self._tzinfo is not None: assert s[-1:] == ")" s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")" @@ -1586,12 +1661,13 @@ def __repr__(self): def __str__(self): "Convert to string, for str()." - return self.isoformat(sep=' ') + return self.isoformat(sep=" ") @classmethod def strptime(cls, date_string, format): - 'string, format -> new datetime parsed from a string (like time.strptime()).' + "string, format -> new datetime parsed from a string (like time.strptime())." import _strptime + return _strptime._strptime_datetime(cls, date_string, format) def utcoffset(self): @@ -1693,19 +1769,33 @@ def _cmp(self, other, allow_mixed=False): base_compare = myoff == otoff if base_compare: - return _cmp((self._year, self._month, self._day, - self._hour, self._minute, self._second, - self._microsecond), - (other._year, other._month, other._day, - other._hour, other._minute, other._second, - other._microsecond)) + return _cmp( + ( + self._year, + self._month, + self._day, + self._hour, + self._minute, + self._second, + self._microsecond, + ), + ( + other._year, + other._month, + other._day, + other._hour, + other._minute, + other._second, + other._microsecond, + ), + ) if myoff is None or otoff is None: if allow_mixed: - return 2 # arbitrary non-zero value + return 2 # arbitrary non-zero value else: raise TypeError("cannot compare naive and aware datetimes") # XXX What follows could be done more efficiently... - diff = self - other # this will take offsets into account + diff = self - other # this will take offsets into account if diff.days < 0: return -1 return diff and 1 or 0 @@ -1714,19 +1804,21 @@ def __add__(self, other): "Add a datetime and a timedelta." if not isinstance(other, timedelta): return NotImplemented - delta = timedelta(self.toordinal(), - hours=self._hour, - minutes=self._minute, - seconds=self._second, - microseconds=self._microsecond) + delta = timedelta( + self.toordinal(), + hours=self._hour, + minutes=self._minute, + seconds=self._second, + microseconds=self._microsecond, + ) delta += other hour, rem = divmod(delta.seconds, 3600) minute, second = divmod(rem, 60) if 0 < delta.days <= _MAXORDINAL: - return datetime.combine(date.fromordinal(delta.days), - time(hour, minute, second, - delta.microseconds, - tzinfo=self._tzinfo)) + return datetime.combine( + date.fromordinal(delta.days), + time(hour, minute, second, delta.microseconds, tzinfo=self._tzinfo), + ) raise OverflowError("result out of range") __radd__ = __add__ @@ -1742,9 +1834,7 @@ def __sub__(self, other): days2 = other.toordinal() secs1 = self._second + self._minute * 60 + self._hour * 3600 secs2 = other._second + other._minute * 60 + other._hour * 3600 - base = timedelta(days1 - days2, - secs1 - secs2, - self._microsecond - other._microsecond) + base = timedelta(days1 - days2, secs1 - secs2, self._microsecond - other._microsecond) if self._tzinfo is other._tzinfo: return base myoff = self.utcoffset() @@ -1769,17 +1859,38 @@ def _getstate(self): yhi, ylo = divmod(self._year, 256) us2, us3 = divmod(self._microsecond, 256) us1, us2 = divmod(us2, 256) - basestate = bytes([yhi, ylo, self._month, self._day, - self._hour, self._minute, self._second, - us1, us2, us3]) + basestate = bytes( + [ + yhi, + ylo, + self._month, + self._day, + self._hour, + self._minute, + self._second, + us1, + us2, + us3, + ] + ) if self._tzinfo is None: return (basestate,) else: return (basestate, self._tzinfo) def __setstate(self, string, tzinfo): - (yhi, ylo, self._month, self._day, self._hour, - self._minute, self._second, us1, us2, us3) = string + ( + yhi, + ylo, + self._month, + self._day, + self._hour, + self._minute, + self._second, + us1, + us2, + us3, + ) = string self._year = yhi * 256 + ylo self._microsecond = (((us1 << 8) | us2) << 8) | us3 if tzinfo is None or isinstance(tzinfo, _tzinfo_class): @@ -1801,17 +1912,19 @@ def _isoweek1monday(year): # XXX This could be done more efficiently THURSDAY = 3 firstday = _ymd2ord(year, 1, 1) - firstweekday = (firstday + 6) % 7 # See weekday() above + firstweekday = (firstday + 6) % 7 # See weekday() above week1monday = firstday - firstweekday if firstweekday > THURSDAY: week1monday += 7 return week1monday + class timezone(tzinfo): - __slots__ = '_offset', '_name' + __slots__ = "_offset", "_name" # Sentinel value to disallow None _Omitted = object() + def __new__(cls, offset, name=_Omitted): if not isinstance(offset, timedelta): raise TypeError("offset must be a timedelta") @@ -1822,13 +1935,15 @@ def __new__(cls, offset, name=_Omitted): elif not isinstance(name, str): raise TypeError("name must be a string") if not cls._minoffset <= offset <= cls._maxoffset: - raise ValueError("offset must be a timedelta" - " strictly between -timedelta(hours=24) and" - " timedelta(hours=24).") - if (offset.microseconds != 0 or - offset.seconds % 60 != 0): - raise ValueError("offset must be a timedelta" - " representing a whole number of minutes") + raise ValueError( + "offset must be a timedelta" + " strictly between -timedelta(hours=24) and" + " timedelta(hours=24)." + ) + if offset.microseconds != 0 or offset.seconds % 60 != 0: + raise ValueError( + "offset must be a timedelta" " representing a whole number of minutes" + ) return cls._create(offset, name) @classmethod @@ -1863,12 +1978,10 @@ def __repr__(self): "datetime.timezone(datetime.timedelta(-1, 68400), 'EST')" """ if self is self.utc: - return 'datetime.timezone.utc' + return "datetime.timezone.utc" if self._name is None: - return "%s(%r)" % ('datetime.' + self.__class__.__name__, - self._offset) - return "%s(%r, %r)" % ('datetime.' + self.__class__.__name__, - self._offset, self._name) + return "%s(%r)" % ("datetime." + self.__class__.__name__, self._offset) + return "%s(%r, %r)" % ("datetime." + self.__class__.__name__, self._offset, self._name) def __str__(self): return self.tzname(None) @@ -1876,31 +1989,26 @@ def __str__(self): def utcoffset(self, dt): if isinstance(dt, datetime) or dt is None: return self._offset - raise TypeError("utcoffset() argument must be a datetime instance" - " or None") + raise TypeError("utcoffset() argument must be a datetime instance" " or None") def tzname(self, dt): if isinstance(dt, datetime) or dt is None: if self._name is None: return self._name_from_offset(self._offset) return self._name - raise TypeError("tzname() argument must be a datetime instance" - " or None") + raise TypeError("tzname() argument must be a datetime instance" " or None") def dst(self, dt): if isinstance(dt, datetime) or dt is None: return None - raise TypeError("dst() argument must be a datetime instance" - " or None") + raise TypeError("dst() argument must be a datetime instance" " or None") def fromutc(self, dt): if isinstance(dt, datetime): if dt.tzinfo is not self: - raise ValueError("fromutc: dt.tzinfo " - "is not self") + raise ValueError("fromutc: dt.tzinfo " "is not self") return dt + self._offset - raise TypeError("fromutc() argument must be a datetime instance" - " or None") + raise TypeError("fromutc() argument must be a datetime instance" " or None") _maxoffset = timedelta(hours=23, minutes=59) _minoffset = -_maxoffset @@ -1908,13 +2016,14 @@ def fromutc(self, dt): @staticmethod def _name_from_offset(delta): if delta < timedelta(0): - sign = '-' + sign = "-" delta = -delta else: - sign = '+' + sign = "+" hours, rest = divmod(delta, timedelta(hours=1)) minutes = rest // timedelta(minutes=1) - return 'UTC{}{:02d}:{:02d}'.format(sign, hours, minutes) + return "UTC{}{:02d}:{:02d}".format(sign, hours, minutes) + timezone.utc = timezone._create(timedelta(0)) timezone.min = timezone._create(timezone._minoffset) @@ -2123,14 +2232,39 @@ def _name_from_offset(delta): pass else: # Clean up unused names - del (_DAYNAMES, _DAYS_BEFORE_MONTH, _DAYS_IN_MONTH, - _DI100Y, _DI400Y, _DI4Y, _MAXORDINAL, _MONTHNAMES, - _build_struct_time, _call_tzinfo_method, _check_date_fields, - _check_time_fields, _check_tzinfo_arg, _check_tzname, - _check_utc_offset, _cmp, _cmperror, _date_class, _days_before_month, - _days_before_year, _days_in_month, _format_time, _is_leap, - _isoweek1monday, _math, _ord2ymd, _time, _time_class, _tzinfo_class, - _wrap_strftime, _ymd2ord) + del ( + _DAYNAMES, + _DAYS_BEFORE_MONTH, + _DAYS_IN_MONTH, + _DI100Y, + _DI400Y, + _DI4Y, + _MAXORDINAL, + _MONTHNAMES, + _build_struct_time, + _call_tzinfo_method, + _check_date_fields, + _check_time_fields, + _check_tzinfo_arg, + _check_tzname, + _check_utc_offset, + _cmp, + _cmperror, + _date_class, + _days_before_month, + _days_before_year, + _days_in_month, + _format_time, + _is_leap, + _isoweek1monday, + _math, + _ord2ymd, + _time, + _time_class, + _tzinfo_class, + _wrap_strftime, + _ymd2ord, + ) # XXX Since import * above excludes names that start with _, # docstring does not get overwritten. In the future, it may be # appropriate to maintain a single module level docstring and diff --git a/datetime/metadata.txt b/unix-ffi/datetime/metadata.txt similarity index 100% rename from datetime/metadata.txt rename to unix-ffi/datetime/metadata.txt diff --git a/unix-ffi/datetime/setup.py b/unix-ffi/datetime/setup.py new file mode 100644 index 000000000..2f502e520 --- /dev/null +++ b/unix-ffi/datetime/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-datetime", + version="3.3.3-1", + description="CPython datetime module ported to MicroPython", + long_description="This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.", + url="https://github.com/micropython/micropython-lib", + author="CPython Developers", + author_email="python-dev@python.org", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="Python", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["datetime"], +) diff --git a/datetime/test_datetime.py b/unix-ffi/datetime/test_datetime.py similarity index 80% rename from datetime/test_datetime.py rename to unix-ffi/datetime/test_datetime.py index 5a6decacd..180ad194f 100644 --- a/datetime/test_datetime.py +++ b/unix-ffi/datetime/test_datetime.py @@ -21,12 +21,11 @@ import time as _time # Needed by test_datetime -#import _strptime +# import _strptime # -pickle_choices = [(pickle, pickle, proto) - for proto in range(pickle.HIGHEST_PROTOCOL + 1)] +pickle_choices = [(pickle, pickle, proto) for proto in range(pickle.HIGHEST_PROTOCOL + 1)] assert len(pickle_choices) == pickle.HIGHEST_PROTOCOL + 1 # An arbitrary collection of objects of non-datetime types, for testing @@ -42,18 +41,19 @@ ############################################################################# # module tests -class TestModule(unittest.TestCase): +class TestModule(unittest.TestCase): def test_constants(self): datetime = datetime_module self.assertEqual(datetime.MINYEAR, 1) self.assertEqual(datetime.MAXYEAR, 9999) + ############################################################################# # tzinfo tests -class FixedOffset(tzinfo): +class FixedOffset(tzinfo): def __init__(self, offset, name, dstoffset=42): if isinstance(offset, int): offset = timedelta(minutes=offset) @@ -62,22 +62,26 @@ def __init__(self, offset, name, dstoffset=42): self.__offset = offset self.__name = name self.__dstoffset = dstoffset + def __repr__(self): return self.__name.lower() + def utcoffset(self, dt): return self.__offset + def tzname(self, dt): return self.__name + def dst(self, dt): return self.__dstoffset -class PicklableFixedOffset(FixedOffset): +class PicklableFixedOffset(FixedOffset): def __init__(self, offset=None, name=None, dstoffset=None): FixedOffset.__init__(self, offset, name, dstoffset) -class TestTZInfo(unittest.TestCase): +class TestTZInfo(unittest.TestCase): def test_non_abstractness(self): # In order to allow subclasses to get pickled, the C implementation # wasn't able to get away with having __init__ raise @@ -93,6 +97,7 @@ class NotEnough(tzinfo): def __init__(self, offset, name): self.__offset = offset self.__name = name + self.assertTrue(issubclass(NotEnough, tzinfo)) ne = NotEnough(3, "NotByALongShot") self.assertIsInstance(ne, tzinfo) @@ -127,9 +132,10 @@ def test_pickling_subclass(self): # Make sure we can pickle/unpickle an instance of a subclass. offset = timedelta(minutes=-300) for otype, args in [ - (PicklableFixedOffset, (offset, 'cookie')), + (PicklableFixedOffset, (offset, "cookie")), (timezone, (offset,)), - (timezone, (offset, "EST"))]: + (timezone, (offset, "EST")), + ]: orig = otype(*args) oname = orig.tzname(None) self.assertIsInstance(orig, tzinfo) @@ -144,51 +150,57 @@ def test_pickling_subclass(self): self.assertEqual(derived.utcoffset(None), offset) self.assertEqual(derived.tzname(None), oname) -class TestTimeZone(unittest.TestCase): +class TestTimeZone(unittest.TestCase): def setUp(self): - self.ACDT = timezone(timedelta(hours=9.5), 'ACDT') - self.EST = timezone(-timedelta(hours=5), 'EST') + self.ACDT = timezone(timedelta(hours=9.5), "ACDT") + self.EST = timezone(-timedelta(hours=5), "EST") self.DT = datetime(2010, 1, 1) def test_str(self): - for tz in [self.ACDT, self.EST, timezone.utc, - timezone.min, timezone.max]: + for tz in [self.ACDT, self.EST, timezone.utc, timezone.min, timezone.max]: self.assertEqual(str(tz), tz.tzname(None)) def test_repr(self): datetime = datetime_module - for tz in [self.ACDT, self.EST, timezone.utc, - timezone.min, timezone.max]: + for tz in [self.ACDT, self.EST, timezone.utc, timezone.min, timezone.max]: # test round-trip tzrep = repr(tz) -# MicroPython doesn't use locals() in eval() + # MicroPython doesn't use locals() in eval() tzrep = tzrep.replace("datetime.", "") self.assertEqual(tz, eval(tzrep)) - def test_class_members(self): limit = timedelta(hours=23, minutes=59) self.assertEqual(timezone.utc.utcoffset(None), ZERO) self.assertEqual(timezone.min.utcoffset(None), -limit) self.assertEqual(timezone.max.utcoffset(None), limit) - def test_constructor(self): self.assertIs(timezone.utc, timezone(timedelta(0))) - self.assertIsNot(timezone.utc, timezone(timedelta(0), 'UTC')) - self.assertEqual(timezone.utc, timezone(timedelta(0), 'UTC')) + self.assertIsNot(timezone.utc, timezone(timedelta(0), "UTC")) + self.assertEqual(timezone.utc, timezone(timedelta(0), "UTC")) # invalid offsets - for invalid in [timedelta(microseconds=1), timedelta(1, 1), - timedelta(seconds=1), timedelta(1), -timedelta(1)]: + for invalid in [ + timedelta(microseconds=1), + timedelta(1, 1), + timedelta(seconds=1), + timedelta(1), + -timedelta(1), + ]: self.assertRaises(ValueError, timezone, invalid) self.assertRaises(ValueError, timezone, -invalid) - with self.assertRaises(TypeError): timezone(None) - with self.assertRaises(TypeError): timezone(42) - with self.assertRaises(TypeError): timezone(ZERO, None) - with self.assertRaises(TypeError): timezone(ZERO, 42) - with self.assertRaises(TypeError): timezone(ZERO, 'ABC', 'extra') + with self.assertRaises(TypeError): + timezone(None) + with self.assertRaises(TypeError): + timezone(42) + with self.assertRaises(TypeError): + timezone(ZERO, None) + with self.assertRaises(TypeError): + timezone(ZERO, 42) + with self.assertRaises(TypeError): + timezone(ZERO, "ABC", "extra") def test_inheritance(self): self.assertIsInstance(timezone.utc, tzinfo) @@ -201,62 +213,66 @@ def test_utcoffset(self): self.assertEqual(offset, timezone(offset).utcoffset(dummy)) self.assertEqual(-offset, timezone(-offset).utcoffset(dummy)) - with self.assertRaises(TypeError): self.EST.utcoffset('') - with self.assertRaises(TypeError): self.EST.utcoffset(5) - + with self.assertRaises(TypeError): + self.EST.utcoffset("") + with self.assertRaises(TypeError): + self.EST.utcoffset(5) def test_dst(self): self.assertIsNone(timezone.utc.dst(self.DT)) - with self.assertRaises(TypeError): self.EST.dst('') - with self.assertRaises(TypeError): self.EST.dst(5) + with self.assertRaises(TypeError): + self.EST.dst("") + with self.assertRaises(TypeError): + self.EST.dst(5) def test_tzname(self): - self.assertEqual('UTC+00:00', timezone(ZERO).tzname(None)) - self.assertEqual('UTC-05:00', timezone(-5 * HOUR).tzname(None)) - self.assertEqual('UTC+09:30', timezone(9.5 * HOUR).tzname(None)) - self.assertEqual('UTC-00:01', timezone(timedelta(minutes=-1)).tzname(None)) - self.assertEqual('XYZ', timezone(-5 * HOUR, 'XYZ').tzname(None)) + self.assertEqual("UTC+00:00", timezone(ZERO).tzname(None)) + self.assertEqual("UTC-05:00", timezone(-5 * HOUR).tzname(None)) + self.assertEqual("UTC+09:30", timezone(9.5 * HOUR).tzname(None)) + self.assertEqual("UTC-00:01", timezone(timedelta(minutes=-1)).tzname(None)) + self.assertEqual("XYZ", timezone(-5 * HOUR, "XYZ").tzname(None)) - with self.assertRaises(TypeError): self.EST.tzname('') - with self.assertRaises(TypeError): self.EST.tzname(5) + with self.assertRaises(TypeError): + self.EST.tzname("") + with self.assertRaises(TypeError): + self.EST.tzname(5) def test_fromutc(self): with self.assertRaises(ValueError): timezone.utc.fromutc(self.DT) with self.assertRaises(TypeError): - timezone.utc.fromutc('not datetime') + timezone.utc.fromutc("not datetime") for tz in [self.EST, self.ACDT, Eastern]: utctime = self.DT.replace(tzinfo=tz) local = tz.fromutc(utctime) self.assertEqual(local - utctime, tz.utcoffset(local)) - self.assertEqual(local, - self.DT.replace(tzinfo=timezone.utc)) + self.assertEqual(local, self.DT.replace(tzinfo=timezone.utc)) def test_comparison(self): self.assertNotEqual(timezone(ZERO), timezone(HOUR)) self.assertEqual(timezone(HOUR), timezone(HOUR)) - self.assertEqual(timezone(-5 * HOUR), timezone(-5 * HOUR, 'EST')) - with self.assertRaises(TypeError): timezone(ZERO) < timezone(ZERO) + self.assertEqual(timezone(-5 * HOUR), timezone(-5 * HOUR, "EST")) + with self.assertRaises(TypeError): + timezone(ZERO) < timezone(ZERO) self.assertIn(timezone(ZERO), {timezone(ZERO)}) self.assertTrue(timezone(ZERO) != None) - self.assertFalse(timezone(ZERO) == None) + self.assertFalse(timezone(ZERO) == None) def test_aware_datetime(self): # test that timezone instances can be used by datetime t = datetime(1, 1, 1) for tz in [timezone.min, timezone.max, timezone.utc]: - self.assertEqual(tz.tzname(t), - t.replace(tzinfo=tz).tzname()) - self.assertEqual(tz.utcoffset(t), - t.replace(tzinfo=tz).utcoffset()) - self.assertEqual(tz.dst(t), - t.replace(tzinfo=tz).dst()) + self.assertEqual(tz.tzname(t), t.replace(tzinfo=tz).tzname()) + self.assertEqual(tz.utcoffset(t), t.replace(tzinfo=tz).utcoffset()) + self.assertEqual(tz.dst(t), t.replace(tzinfo=tz).dst()) + ############################################################################# # Base class for testing a particular aspect of timedelta, time, date and # datetime comparisons. + class HarmlessMixedComparison: # Test that __eq__ and __ne__ don't complain for mixed-type comparisons. @@ -287,9 +303,11 @@ def test_harmful_mixed_comparison(self): self.assertRaises(TypeError, lambda: () > me) self.assertRaises(TypeError, lambda: () >= me) + ############################################################################# # timedelta tests + class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): theclass = timedelta @@ -299,8 +317,10 @@ def test_constructor(self): td = timedelta # Check keyword args to constructor - eq(td(), td(weeks=0, days=0, hours=0, minutes=0, seconds=0, - milliseconds=0, microseconds=0)) + eq( + td(), + td(weeks=0, days=0, hours=0, minutes=0, seconds=0, milliseconds=0, microseconds=0), + ) eq(td(1), td(days=1)) eq(td(0, 1), td(seconds=1)) eq(td(0, 0, 1), td(microseconds=1)) @@ -312,10 +332,10 @@ def test_constructor(self): eq(td(milliseconds=1), td(microseconds=1000)) # Check float args to constructor - eq(td(weeks=1.0/7), td(days=1)) - eq(td(days=1.0/24), td(hours=1)) - eq(td(hours=1.0/60), td(minutes=1)) - eq(td(minutes=1.0/60), td(seconds=1)) + eq(td(weeks=1.0 / 7), td(days=1)) + eq(td(days=1.0 / 24), td(hours=1)) + eq(td(hours=1.0 / 60), td(minutes=1)) + eq(td(minutes=1.0 / 60), td(seconds=1)) eq(td(seconds=0.001), td(milliseconds=1)) eq(td(milliseconds=0.001), td(microseconds=1)) @@ -323,87 +343,85 @@ def test_computations(self): eq = self.assertEqual td = timedelta - a = td(7) # One week - b = td(0, 60) # One minute - c = td(0, 0, 1000) # One millisecond - eq(a+b+c, td(7, 60, 1000)) - eq(a-b, td(6, 24*3600 - 60)) - eq(b.__rsub__(a), td(6, 24*3600 - 60)) + a = td(7) # One week + b = td(0, 60) # One minute + c = td(0, 0, 1000) # One millisecond + eq(a + b + c, td(7, 60, 1000)) + eq(a - b, td(6, 24 * 3600 - 60)) + eq(b.__rsub__(a), td(6, 24 * 3600 - 60)) eq(-a, td(-7)) eq(+a, td(7)) - eq(-b, td(-1, 24*3600 - 60)) - eq(-c, td(-1, 24*3600 - 1, 999000)) + eq(-b, td(-1, 24 * 3600 - 60)) + eq(-c, td(-1, 24 * 3600 - 1, 999000)) eq(abs(a), a) eq(abs(-a), a) - eq(td(6, 24*3600), a) - eq(td(0, 0, 60*1000000), b) - eq(a*10, td(70)) - eq(a*10, 10*a) - eq(a*10, 10*a) - eq(b*10, td(0, 600)) - eq(10*b, td(0, 600)) - eq(b*10, td(0, 600)) - eq(c*10, td(0, 0, 10000)) - eq(10*c, td(0, 0, 10000)) - eq(c*10, td(0, 0, 10000)) - eq(a*-1, -a) - eq(b*-2, -b-b) - eq(c*-2, -c+-c) - eq(b*(60*24), (b*60)*24) - eq(b*(60*24), (60*b)*24) - eq(c*1000, td(0, 1)) - eq(1000*c, td(0, 1)) - eq(a//7, td(1)) - eq(b//10, td(0, 6)) - eq(c//1000, td(0, 0, 1)) - eq(a//10, td(0, 7*24*360)) - eq(a//3600000, td(0, 0, 7*24*1000)) - eq(a/0.5, td(14)) - eq(b/0.5, td(0, 120)) - eq(a/7, td(1)) - eq(b/10, td(0, 6)) - eq(c/1000, td(0, 0, 1)) - eq(a/10, td(0, 7*24*360)) - eq(a/3600000, td(0, 0, 7*24*1000)) + eq(td(6, 24 * 3600), a) + eq(td(0, 0, 60 * 1000000), b) + eq(a * 10, td(70)) + eq(a * 10, 10 * a) + eq(a * 10, 10 * a) + eq(b * 10, td(0, 600)) + eq(10 * b, td(0, 600)) + eq(b * 10, td(0, 600)) + eq(c * 10, td(0, 0, 10000)) + eq(10 * c, td(0, 0, 10000)) + eq(c * 10, td(0, 0, 10000)) + eq(a * -1, -a) + eq(b * -2, -b - b) + eq(c * -2, -c + -c) + eq(b * (60 * 24), (b * 60) * 24) + eq(b * (60 * 24), (60 * b) * 24) + eq(c * 1000, td(0, 1)) + eq(1000 * c, td(0, 1)) + eq(a // 7, td(1)) + eq(b // 10, td(0, 6)) + eq(c // 1000, td(0, 0, 1)) + eq(a // 10, td(0, 7 * 24 * 360)) + eq(a // 3600000, td(0, 0, 7 * 24 * 1000)) + eq(a / 0.5, td(14)) + eq(b / 0.5, td(0, 120)) + eq(a / 7, td(1)) + eq(b / 10, td(0, 6)) + eq(c / 1000, td(0, 0, 1)) + eq(a / 10, td(0, 7 * 24 * 360)) + eq(a / 3600000, td(0, 0, 7 * 24 * 1000)) # Multiplication by float us = td(microseconds=1) - eq((3*us) * 0.5, 2*us) - eq((5*us) * 0.5, 2*us) - eq(0.5 * (3*us), 2*us) - eq(0.5 * (5*us), 2*us) - eq((-3*us) * 0.5, -2*us) - eq((-5*us) * 0.5, -2*us) + eq((3 * us) * 0.5, 2 * us) + eq((5 * us) * 0.5, 2 * us) + eq(0.5 * (3 * us), 2 * us) + eq(0.5 * (5 * us), 2 * us) + eq((-3 * us) * 0.5, -2 * us) + eq((-5 * us) * 0.5, -2 * us) # Division by int and float - eq((3*us) / 2, 2*us) - eq((5*us) / 2, 2*us) - eq((-3*us) / 2.0, -2*us) - eq((-5*us) / 2.0, -2*us) - eq((3*us) / -2, -2*us) - eq((5*us) / -2, -2*us) - eq((3*us) / -2.0, -2*us) - eq((5*us) / -2.0, -2*us) + eq((3 * us) / 2, 2 * us) + eq((5 * us) / 2, 2 * us) + eq((-3 * us) / 2.0, -2 * us) + eq((-5 * us) / 2.0, -2 * us) + eq((3 * us) / -2, -2 * us) + eq((5 * us) / -2, -2 * us) + eq((3 * us) / -2.0, -2 * us) + eq((5 * us) / -2.0, -2 * us) for i in range(-10, 10): - eq((i*us/3)//us, round(i/3)) + eq((i * us / 3) // us, round(i / 3)) for i in range(-10, 10): - eq((i*us/-3)//us, round(i/-3)) + eq((i * us / -3) // us, round(i / -3)) # Issue #11576 - eq(td(999999999, 86399, 999999) - td(999999999, 86399, 999998), - td(0, 0, 1)) - eq(td(999999999, 1, 1) - td(999999999, 1, 0), - td(0, 0, 1)) + eq(td(999999999, 86399, 999999) - td(999999999, 86399, 999998), td(0, 0, 1)) + eq(td(999999999, 1, 1) - td(999999999, 1, 0), td(0, 0, 1)) def test_disallowed_computations(self): a = timedelta(42) # Add/sub ints or floats should be illegal for i in 1, 1.0: - self.assertRaises(TypeError, lambda: a+i) - self.assertRaises(TypeError, lambda: a-i) - self.assertRaises(TypeError, lambda: i+a) - self.assertRaises(TypeError, lambda: i-a) + self.assertRaises(TypeError, lambda: a + i) + self.assertRaises(TypeError, lambda: a - i) + self.assertRaises(TypeError, lambda: i + a) + self.assertRaises(TypeError, lambda: i - a) # Division of int by timedelta doesn't make sense. # Division by zero doesn't make sense. @@ -412,7 +430,7 @@ def test_disallowed_computations(self): self.assertRaises(ZeroDivisionError, lambda: a // zero) self.assertRaises(ZeroDivisionError, lambda: a / zero) self.assertRaises(ZeroDivisionError, lambda: a / 0.0) - self.assertRaises(TypeError, lambda: a / '') + self.assertRaises(TypeError, lambda: a / "") @support.requires_IEEE_754 def test_disallowed_special(self): @@ -440,27 +458,31 @@ def test_total_seconds(self): self.assertEqual(td.total_seconds(), td / timedelta(seconds=1)) def test_carries(self): - t1 = timedelta(days=100, - weeks=-7, - hours=-24*(100-49), - minutes=-3, - seconds=12, - microseconds=(3*60 - 12) * 1e6 + 1) + t1 = timedelta( + days=100, + weeks=-7, + hours=-24 * (100 - 49), + minutes=-3, + seconds=12, + microseconds=(3 * 60 - 12) * 1e6 + 1, + ) t2 = timedelta(microseconds=1) self.assertEqual(t1, t2) def test_hash_equality(self): - t1 = timedelta(days=100, - weeks=-7, - hours=-24*(100-49), - minutes=-3, - seconds=12, - microseconds=(3*60 - 12) * 1000000) + t1 = timedelta( + days=100, + weeks=-7, + hours=-24 * (100 - 49), + minutes=-3, + seconds=12, + microseconds=(3 * 60 - 12) * 1000000, + ) t2 = timedelta() self.assertEqual(hash(t1), hash(t2)) t1 += timedelta(weeks=7) - t2 += timedelta(days=7*7) + t2 += timedelta(days=7 * 7) self.assertEqual(t1, t2) self.assertEqual(hash(t1), hash(t2)) @@ -489,7 +511,7 @@ def test_compare(self): self.assertTrue(not t1 > t2) for args in (3, 3, 3), (2, 4, 4), (2, 3, 5): - t2 = timedelta(*args) # this is larger than t1 + t2 = timedelta(*args) # this is larger than t1 self.assertTrue(t1 < t2) self.assertTrue(t2 > t1) self.assertTrue(t1 <= t2) @@ -529,35 +551,33 @@ def test_str(self): eq(str(td(hours=12, minutes=58, seconds=59)), "12:58:59") eq(str(td(hours=2, minutes=3, seconds=4)), "2:03:04") - eq(str(td(weeks=-30, hours=23, minutes=12, seconds=34)), - "-210 days, 23:12:34") + eq(str(td(weeks=-30, hours=23, minutes=12, seconds=34)), "-210 days, 23:12:34") eq(str(td(milliseconds=1)), "0:00:00.001000") eq(str(td(microseconds=3)), "0:00:00.000003") - eq(str(td(days=999999999, hours=23, minutes=59, seconds=59, - microseconds=999999)), - "999999999 days, 23:59:59.999999") + eq( + str(td(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)), + "999999999 days, 23:59:59.999999", + ) def test_repr(self): - name = 'datetime.' + self.theclass.__name__ - self.assertEqual(repr(self.theclass(1)), - "%s(1)" % name) - self.assertEqual(repr(self.theclass(10, 2)), - "%s(10, 2)" % name) - self.assertEqual(repr(self.theclass(-10, 2, 400000)), - "%s(-10, 2, 400000)" % name) + name = "datetime." + self.theclass.__name__ + self.assertEqual(repr(self.theclass(1)), "%s(1)" % name) + self.assertEqual(repr(self.theclass(10, 2)), "%s(10, 2)" % name) + self.assertEqual(repr(self.theclass(-10, 2, 400000)), "%s(-10, 2, 400000)" % name) def test_roundtrip(self): - for td in (timedelta(days=999999999, hours=23, minutes=59, - seconds=59, microseconds=999999), - timedelta(days=-999999999), - timedelta(days=-999999999, seconds=1), - timedelta(days=1, seconds=2, microseconds=3)): + for td in ( + timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999), + timedelta(days=-999999999), + timedelta(days=-999999999, seconds=1), + timedelta(days=1, seconds=2, microseconds=3), + ): # Verify td -> string -> td identity. s = repr(td) - self.assertTrue(s.startswith('datetime.')) + self.assertTrue(s.startswith("datetime.")) s = s[9:] td2 = eval(s) self.assertEqual(td, td2) @@ -572,7 +592,7 @@ def test_resolution_info(self): self.assertIsInstance(timedelta.resolution, timedelta) self.assertTrue(timedelta.max > timedelta.min) self.assertEqual(timedelta.min, timedelta(-999999999)) - self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1)) + self.assertEqual(timedelta.max, timedelta(999999999, 24 * 3600 - 1, 1e6 - 1)) self.assertEqual(timedelta.resolution, timedelta(0, 0, 1)) def test_overflow(self): @@ -591,7 +611,7 @@ def test_overflow(self): self.assertRaises(OverflowError, lambda: -timedelta.max) day = timedelta(1) - self.assertRaises(OverflowError, day.__mul__, 10**9) + self.assertRaises(OverflowError, day.__mul__, 10 ** 9) self.assertRaises(OverflowError, day.__mul__, 1e9) self.assertRaises(OverflowError, day.__truediv__, 1e-20) self.assertRaises(OverflowError, day.__truediv__, 1e-10) @@ -608,26 +628,25 @@ def test_microsecond_rounding(self): eq = self.assertEqual # Single-field rounding. - eq(td(milliseconds=0.4/1000), td(0)) # rounds to 0 - eq(td(milliseconds=-0.4/1000), td(0)) # rounds to 0 - eq(td(milliseconds=0.6/1000), td(microseconds=1)) - eq(td(milliseconds=-0.6/1000), td(microseconds=-1)) + eq(td(milliseconds=0.4 / 1000), td(0)) # rounds to 0 + eq(td(milliseconds=-0.4 / 1000), td(0)) # rounds to 0 + eq(td(milliseconds=0.6 / 1000), td(microseconds=1)) + eq(td(milliseconds=-0.6 / 1000), td(microseconds=-1)) # Rounding due to contributions from more than one field. us_per_hour = 3600e6 us_per_day = us_per_hour * 24 - eq(td(days=.4/us_per_day), td(0)) - eq(td(hours=.2/us_per_hour), td(0)) - eq(td(days=.4/us_per_day, hours=.2/us_per_hour), td(microseconds=1)) + eq(td(days=0.4 / us_per_day), td(0)) + eq(td(hours=0.2 / us_per_hour), td(0)) + eq(td(days=0.4 / us_per_day, hours=0.2 / us_per_hour), td(microseconds=1)) - eq(td(days=-.4/us_per_day), td(0)) - eq(td(hours=-.2/us_per_hour), td(0)) - eq(td(days=-.4/us_per_day, hours=-.2/us_per_hour), td(microseconds=-1)) + eq(td(days=-0.4 / us_per_day), td(0)) + eq(td(hours=-0.2 / us_per_hour), td(0)) + eq(td(days=-0.4 / us_per_day, hours=-0.2 / us_per_hour), td(microseconds=-1)) def test_massive_normalization(self): td = timedelta(microseconds=-1) - self.assertEqual((td.days, td.seconds, td.microseconds), - (-1, 24*3600-1, 999999)) + self.assertEqual((td.days, td.seconds, td.microseconds), (-1, 24 * 3600 - 1, 999999)) def test_bool(self): self.assertTrue(timedelta(1)) @@ -637,16 +656,13 @@ def test_bool(self): self.assertTrue(not timedelta(0)) def test_subclass_timedelta(self): - class T(timedelta): @staticmethod def from_td(td): return T(td.days, td.seconds, td.microseconds) def as_hours(self): - sum = (self.days * 24 + - self.seconds / 3600.0 + - self.microseconds / 3600e6) + sum = self.days * 24 + self.seconds / 3600.0 + self.microseconds / 3600e6 return round(sum) t1 = T(days=1) @@ -693,7 +709,7 @@ def test_remainder(self): self.assertEqual(r, timedelta(seconds=30)) t = timedelta(minutes=-2, seconds=30) - r = t % minute + r = t % minute self.assertEqual(r, timedelta(seconds=30)) zerotd = timedelta(0) @@ -722,14 +738,14 @@ def test_divmod(self): ############################################################################# # date tests + class TestDateOnly(unittest.TestCase): # Tests here won't pass if also run on datetime objects, so don't # subclass this to test datetimes too. def test_delta_non_days_ignored(self): dt = date(2000, 1, 2) - delta = timedelta(days=1, hours=2, minutes=3, seconds=4, - microseconds=5) + delta = timedelta(days=1, hours=2, minutes=3, seconds=4, microseconds=5) days = timedelta(delta.days) self.assertEqual(days, timedelta(1)) @@ -755,9 +771,11 @@ def test_delta_non_days_ignored(self): dt2 = dt - delta self.assertEqual(dt2, dt - days) + class SubclassDate(date): sub_var = 1 + class TestDate(HarmlessMixedComparison, unittest.TestCase): # Tests here should pass for both dates and datetimes, except for a # few tests that TestDateTime overrides. @@ -771,11 +789,10 @@ def test_basic_attributes(self): self.assertEqual(dt.day, 1) def test_roundtrip(self): - for dt in (self.theclass(1, 2, 3), - self.theclass.today()): + for dt in (self.theclass(1, 2, 3), self.theclass.today()): # Verify dt -> string -> date identity. s = repr(dt) - self.assertTrue(s.startswith('datetime.')) + self.assertTrue(s.startswith("datetime.")) s = s[9:] dt2 = eval(s) self.assertEqual(dt, dt2) @@ -786,18 +803,20 @@ def test_roundtrip(self): def test_ordinal_conversions(self): # Check some fixed values. - for y, m, d, n in [(1, 1, 1, 1), # calendar origin - (1, 12, 31, 365), - (2, 1, 1, 366), - # first example from "Calendrical Calculations" - (1945, 11, 12, 710347)]: + for y, m, d, n in [ + (1, 1, 1, 1), # calendar origin + (1, 12, 31, 365), + (2, 1, 1, 366), + # first example from "Calendrical Calculations" + (1945, 11, 12, 710347), + ]: d = self.theclass(y, m, d) self.assertEqual(n, d.toordinal()) fromord = self.theclass.fromordinal(n) self.assertEqual(d, fromord) if hasattr(fromord, "hour"): - # if we're checking something fancier than a date, verify - # the extra fields have been zeroed out + # if we're checking something fancier than a date, verify + # the extra fields have been zeroed out self.assertEqual(fromord.hour, 0) self.assertEqual(fromord.minute, 0) self.assertEqual(fromord.second, 0) @@ -805,7 +824,7 @@ def test_ordinal_conversions(self): # Check first and last days of year spottily across the whole # range of years supported. - for year in range(MINYEAR, MAXYEAR+1, 7): + for year in range(MINYEAR, MAXYEAR + 1, 7): # Verify (year, 1, 1) -> ordinal -> y, m, d is identity. d = self.theclass(year, 1, 1) n = d.toordinal() @@ -813,10 +832,10 @@ def test_ordinal_conversions(self): self.assertEqual(d, d2) # Verify that moving back a day gets to the end of year-1. if year > 1: - d = self.theclass.fromordinal(n-1) - d2 = self.theclass(year-1, 12, 31) + d = self.theclass.fromordinal(n - 1) + d2 = self.theclass(year - 1, 12, 31) self.assertEqual(d, d2) - self.assertEqual(d2.toordinal(), n-1) + self.assertEqual(d2.toordinal(), n - 1) # Test every day in a leap-year and a non-leap year. dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] @@ -825,7 +844,7 @@ def test_ordinal_conversions(self): for month, maxday in zip(range(1, 13), dim): if month == 2 and isleap: maxday += 1 - for day in range(1, maxday+1): + for day in range(1, maxday + 1): d = self.theclass(year, month, day) self.assertEqual(d.toordinal(), n) self.assertEqual(d, self.theclass.fromordinal(n)) @@ -860,17 +879,17 @@ def test_bad_constructor_arguments(self): # bad years self.theclass(MINYEAR, 1, 1) # no exception self.theclass(MAXYEAR, 1, 1) # no exception - self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1) - self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1) + self.assertRaises(ValueError, self.theclass, MINYEAR - 1, 1, 1) + self.assertRaises(ValueError, self.theclass, MAXYEAR + 1, 1, 1) # bad months - self.theclass(2000, 1, 1) # no exception - self.theclass(2000, 12, 1) # no exception + self.theclass(2000, 1, 1) # no exception + self.theclass(2000, 12, 1) # no exception self.assertRaises(ValueError, self.theclass, 2000, 0, 1) self.assertRaises(ValueError, self.theclass, 2000, 13, 1) # bad days - self.theclass(2000, 2, 29) # no exception - self.theclass(2004, 2, 29) # no exception - self.theclass(2400, 2, 29) # no exception + self.theclass(2000, 2, 29) # no exception + self.theclass(2004, 2, 29) # no exception + self.theclass(2400, 2, 29) # no exception self.assertRaises(ValueError, self.theclass, 2000, 2, 30) self.assertRaises(ValueError, self.theclass, 2001, 2, 29) self.assertRaises(ValueError, self.theclass, 2100, 2, 29) @@ -891,9 +910,9 @@ def test_hash_equality(self): self.assertEqual(dic[d], 2) self.assertEqual(dic[e], 2) - d = self.theclass(2001, 1, 1) + d = self.theclass(2001, 1, 1) # same thing - e = self.theclass(2001, 1, 1) + e = self.theclass(2001, 1, 1) self.assertEqual(d, e) self.assertEqual(hash(d), hash(e)) @@ -906,10 +925,10 @@ def test_hash_equality(self): def test_computations(self): a = self.theclass(2002, 1, 31) b = self.theclass(1956, 1, 31) - c = self.theclass(2001,2,1) + c = self.theclass(2001, 2, 1) - diff = a-b - self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4))) + diff = a - b + self.assertEqual(diff.days, 46 * 365 + len(range(1956, 2002, 4))) self.assertEqual(diff.seconds, 0) self.assertEqual(diff.microseconds, 0) @@ -922,8 +941,8 @@ def test_computations(self): self.assertEqual(-day + a, self.theclass(2002, 3, 1)) self.assertEqual(a + week, self.theclass(2002, 3, 9)) self.assertEqual(a - week, self.theclass(2002, 2, 23)) - self.assertEqual(a + 52*week, self.theclass(2003, 3, 1)) - self.assertEqual(a - 52*week, self.theclass(2001, 3, 3)) + self.assertEqual(a + 52 * week, self.theclass(2003, 3, 1)) + self.assertEqual(a - 52 * week, self.theclass(2001, 3, 3)) self.assertEqual((a + week) - a, week) self.assertEqual((a + day) - a, day) self.assertEqual((a - week) - a, -week) @@ -936,10 +955,10 @@ def test_computations(self): # Add/sub ints or floats should be illegal for i in 1, 1.0: - self.assertRaises(TypeError, lambda: a+i) - self.assertRaises(TypeError, lambda: a-i) - self.assertRaises(TypeError, lambda: i+a) - self.assertRaises(TypeError, lambda: i-a) + self.assertRaises(TypeError, lambda: a + i) + self.assertRaises(TypeError, lambda: a - i) + self.assertRaises(TypeError, lambda: i + a) + self.assertRaises(TypeError, lambda: i - a) # delta - date is senseless. self.assertRaises(TypeError, lambda: day - a) @@ -985,8 +1004,7 @@ def test_insane_fromtimestamp(self): # exempt such platforms (provided they return reasonable # results!). for insane in -1e200, 1e200: - self.assertRaises(OverflowError, self.theclass.fromtimestamp, - insane) + self.assertRaises(OverflowError, self.theclass.fromtimestamp, insane) def test_today(self): import time @@ -1013,34 +1031,33 @@ def test_today(self): # It worked or it didn't. If it didn't, assume it's reason #2, and # let the test pass if they're within half a second of each other. - self.assertTrue(today == todayagain or - abs(todayagain - today) < timedelta(seconds=0.5)) + self.assertTrue(today == todayagain or abs(todayagain - today) < timedelta(seconds=0.5)) def test_weekday(self): for i in range(7): # March 4, 2002 is a Monday - self.assertEqual(self.theclass(2002, 3, 4+i).weekday(), i) - self.assertEqual(self.theclass(2002, 3, 4+i).isoweekday(), i+1) + self.assertEqual(self.theclass(2002, 3, 4 + i).weekday(), i) + self.assertEqual(self.theclass(2002, 3, 4 + i).isoweekday(), i + 1) # January 2, 1956 is a Monday - self.assertEqual(self.theclass(1956, 1, 2+i).weekday(), i) - self.assertEqual(self.theclass(1956, 1, 2+i).isoweekday(), i+1) + self.assertEqual(self.theclass(1956, 1, 2 + i).weekday(), i) + self.assertEqual(self.theclass(1956, 1, 2 + i).isoweekday(), i + 1) def test_isocalendar(self): # Check examples from # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for i in range(7): - d = self.theclass(2003, 12, 22+i) - self.assertEqual(d.isocalendar(), (2003, 52, i+1)) + d = self.theclass(2003, 12, 22 + i) + self.assertEqual(d.isocalendar(), (2003, 52, i + 1)) d = self.theclass(2003, 12, 29) + timedelta(i) - self.assertEqual(d.isocalendar(), (2004, 1, i+1)) - d = self.theclass(2004, 1, 5+i) - self.assertEqual(d.isocalendar(), (2004, 2, i+1)) - d = self.theclass(2009, 12, 21+i) - self.assertEqual(d.isocalendar(), (2009, 52, i+1)) + self.assertEqual(d.isocalendar(), (2004, 1, i + 1)) + d = self.theclass(2004, 1, 5 + i) + self.assertEqual(d.isocalendar(), (2004, 2, i + 1)) + d = self.theclass(2009, 12, 21 + i) + self.assertEqual(d.isocalendar(), (2009, 52, i + 1)) d = self.theclass(2009, 12, 28) + timedelta(i) - self.assertEqual(d.isocalendar(), (2009, 53, i+1)) - d = self.theclass(2010, 1, 4+i) - self.assertEqual(d.isocalendar(), (2010, 1, i+1)) + self.assertEqual(d.isocalendar(), (2009, 53, i + 1)) + d = self.theclass(2010, 1, 4 + i) + self.assertEqual(d.isocalendar(), (2010, 1, i + 1)) def test_iso_long_years(self): # Calculate long ISO years and compare to table from @@ -1073,8 +1090,8 @@ def test_iso_long_years(self): iso_long_years = sorted(map(int, ISO_LONG_YEARS_TABLE.split())) L = [] for i in range(400): - d = self.theclass(2000+i, 12, 31) - d1 = self.theclass(1600+i, 12, 31) + d = self.theclass(2000 + i, 12, 31) + d1 = self.theclass(1600 + i, 12, 31) self.assertEqual(d.isocalendar()[1:], d1.isocalendar()[1:]) if d.isocalendar()[1] == 53: L.append(i) @@ -1091,12 +1108,12 @@ def test_ctime(self): def test_strftime(self): t = self.theclass(2005, 3, 2) self.assertEqual(t.strftime("m:%m d:%d y:%y"), "m:03 d:02 y:05") - self.assertEqual(t.strftime(""), "") # SF bug #761337 -# self.assertEqual(t.strftime('x'*1000), 'x'*1000) # SF bug #1556784 + self.assertEqual(t.strftime(""), "") # SF bug #761337 + # self.assertEqual(t.strftime('x'*1000), 'x'*1000) # SF bug #1556784 - self.assertRaises(TypeError, t.strftime) # needs an arg - self.assertRaises(TypeError, t.strftime, "one", "two") # too many args - self.assertRaises(TypeError, t.strftime, 42) # arg wrong type + self.assertRaises(TypeError, t.strftime) # needs an arg + self.assertRaises(TypeError, t.strftime, "one", "two") # too many args + self.assertRaises(TypeError, t.strftime, 42) # arg wrong type # test that unicode input is allowed (issue 2782) self.assertEqual(t.strftime("%m"), "03") @@ -1104,49 +1121,51 @@ def test_strftime(self): # A naive object replaces %z and %Z w/ empty strings. self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''") - #make sure that invalid format specifiers are handled correctly - #self.assertRaises(ValueError, t.strftime, "%e") - #self.assertRaises(ValueError, t.strftime, "%") - #self.assertRaises(ValueError, t.strftime, "%#") + # make sure that invalid format specifiers are handled correctly + # self.assertRaises(ValueError, t.strftime, "%e") + # self.assertRaises(ValueError, t.strftime, "%") + # self.assertRaises(ValueError, t.strftime, "%#") - #oh well, some systems just ignore those invalid ones. - #at least, excercise them to make sure that no crashes - #are generated + # oh well, some systems just ignore those invalid ones. + # at least, excercise them to make sure that no crashes + # are generated for f in ["%e", "%", "%#"]: try: t.strftime(f) except ValueError: pass - #check that this standard extension works + # check that this standard extension works t.strftime("%f") - def test_format(self): dt = self.theclass(2007, 9, 10) - self.assertEqual(dt.__format__(''), str(dt)) + self.assertEqual(dt.__format__(""), str(dt)) # check that a derived class's __str__() gets called class A(self.theclass): def __str__(self): - return 'A' + return "A" + a = A(2007, 9, 10) - self.assertEqual(a.__format__(''), 'A') + self.assertEqual(a.__format__(""), "A") # check that a derived class's strftime gets called class B(self.theclass): def strftime(self, format_spec): - return 'B' + return "B" + b = B(2007, 9, 10) - self.assertEqual(b.__format__(''), str(dt)) + self.assertEqual(b.__format__(""), str(dt)) - for fmt in ["m:%m d:%d y:%y", - "m:%m d:%d y:%y H:%H M:%M S:%S", - "%z %Z", - ]: + for fmt in [ + "m:%m d:%d y:%y", + "m:%m d:%d y:%y H:%H M:%M S:%S", + "%z %Z", + ]: self.assertEqual(dt.__format__(fmt), dt.strftime(fmt)) self.assertEqual(a.__format__(fmt), dt.strftime(fmt)) - self.assertEqual(b.__format__(fmt), 'B') + self.assertEqual(b.__format__(fmt), "B") def test_resolution_info(self): # XXX: Should min and max respect subclassing? @@ -1162,7 +1181,7 @@ def test_resolution_info(self): def test_extreme_timedelta(self): big = self.theclass.max - self.theclass.min # 3652058 days, 23 hours, 59 minutes, 59 seconds, 999999 microseconds - n = (big.days*24*3600 + big.seconds)*1000000 + big.microseconds + n = (big.days * 24 * 3600 + big.seconds) * 1000000 + big.microseconds # n == 315537897599999999 ~= 2**58.13 justasbig = timedelta(0, 0, n) self.assertEqual(big, justasbig) @@ -1172,26 +1191,26 @@ def test_extreme_timedelta(self): def test_timetuple(self): for i in range(7): # January 2, 1956 is a Monday (0) - d = self.theclass(1956, 1, 2+i) + d = self.theclass(1956, 1, 2 + i) t = d.timetuple() - self.assertEqual(t, (1956, 1, 2+i, 0, 0, 0, i, 2+i, -1)) + self.assertEqual(t, (1956, 1, 2 + i, 0, 0, 0, i, 2 + i, -1)) # February 1, 1956 is a Wednesday (2) - d = self.theclass(1956, 2, 1+i) + d = self.theclass(1956, 2, 1 + i) t = d.timetuple() - self.assertEqual(t, (1956, 2, 1+i, 0, 0, 0, (2+i)%7, 32+i, -1)) + self.assertEqual(t, (1956, 2, 1 + i, 0, 0, 0, (2 + i) % 7, 32 + i, -1)) # March 1, 1956 is a Thursday (3), and is the 31+29+1 = 61st day # of the year. - d = self.theclass(1956, 3, 1+i) + d = self.theclass(1956, 3, 1 + i) t = d.timetuple() - self.assertEqual(t, (1956, 3, 1+i, 0, 0, 0, (3+i)%7, 61+i, -1)) + self.assertEqual(t, (1956, 3, 1 + i, 0, 0, 0, (3 + i) % 7, 61 + i, -1)) self.assertEqual(t.tm_year, 1956) self.assertEqual(t.tm_mon, 3) - self.assertEqual(t.tm_mday, 1+i) + self.assertEqual(t.tm_mday, 1 + i) self.assertEqual(t.tm_hour, 0) self.assertEqual(t.tm_min, 0) self.assertEqual(t.tm_sec, 0) - self.assertEqual(t.tm_wday, (3+i)%7) - self.assertEqual(t.tm_yday, 61+i) + self.assertEqual(t.tm_wday, (3 + i) % 7) + self.assertEqual(t.tm_yday, 61 + i) self.assertEqual(t.tm_isdst, -1) def test_pickling(self): @@ -1213,7 +1232,7 @@ def test_compare(self): self.assertTrue(not t1 > t2) for args in (3, 3, 3), (2, 4, 4), (2, 3, 5): - t2 = self.theclass(*args) # this is larger than t1 + t2 = self.theclass(*args) # this is larger than t1 self.assertTrue(t1 < t2) self.assertTrue(t2 > t1) self.assertTrue(t1 <= t2) @@ -1273,14 +1292,19 @@ class SomeClass: class LargerThanAnything: def __lt__(self, other): return False + def __le__(self, other): return isinstance(other, LargerThanAnything) + def __eq__(self, other): return isinstance(other, LargerThanAnything) + def __ne__(self, other): return not isinstance(other, LargerThanAnything) + def __gt__(self, other): return not isinstance(other, LargerThanAnything) + def __ge__(self, other): return True @@ -1289,7 +1313,7 @@ def __ge__(self, other): self.assertEqual(their == our, False) self.assertEqual(our != their, True) self.assertEqual(their != our, True) -# self.assertEqual(our < their, True) + # self.assertEqual(our < their, True) self.assertEqual(their < our, False) def test_bool(self): @@ -1304,11 +1328,11 @@ def test_strftime_y2k(self): # padded to 4 digits across platforms. The C standard # assumes year >= 1900, so it does not specify the number # of digits. - if d.strftime("%Y") != '%04d' % y: + if d.strftime("%Y") != "%04d" % y: # Year 42 returns '42', not padded - self.assertEqual(d.strftime("%Y"), '%d' % y) + self.assertEqual(d.strftime("%Y"), "%d" % y) # '0042' is obtained anyway - self.assertEqual(d.strftime("%4Y"), '%04d' % y) + self.assertEqual(d.strftime("%4Y"), "%04d" % y) def test_replace(self): cls = self.theclass @@ -1317,9 +1341,7 @@ def test_replace(self): self.assertEqual(base, base.replace()) i = 0 - for name, newval in (("year", 2), - ("month", 3), - ("day", 4)): + for name, newval in (("year", 2), ("month", 3), ("day", 4)): newargs = args[:] newargs[i] = newval expected = cls(*newargs) @@ -1332,13 +1354,12 @@ def test_replace(self): self.assertRaises(ValueError, base.replace, year=2001) def test_subclass_date(self): - class C(self.theclass): theAnswer = 42 def __new__(cls, *args, **kws): temp = kws.copy() - extra = temp.pop('extra') + extra = temp.pop("extra") result = self.theclass.__new__(cls, *args, **temp) result.extra = extra return result @@ -1349,7 +1370,7 @@ def newmeth(self, start): args = 2003, 4, 14 dt1 = self.theclass(*args) - dt2 = C(*args, **{'extra': 7}) + dt2 = C(*args, **{"extra": 7}) self.assertEqual(dt2.__class__, C) self.assertEqual(dt2.theAnswer, 42) @@ -1376,15 +1397,13 @@ def test_backdoor_resistance(self): # The constructor doesn't want to burn the time to validate all # fields, but does check the month field. This stops, e.g., # datetime.datetime('1995-03-25') from yielding an insane object. - base = b'1995-03-25' + base = b"1995-03-25" if not issubclass(self.theclass, datetime): base = base[:4] - for month_byte in b'9', b'\0', b'\r', b'\xff': - self.assertRaises(TypeError, self.theclass, - base[:2] + month_byte + base[3:]) + for month_byte in b"9", b"\0", b"\r", b"\xff": + self.assertRaises(TypeError, self.theclass, base[:2] + month_byte + base[3:]) # Good bytes, but bad tzinfo: - self.assertRaises(TypeError, self.theclass, - bytes([1] * len(base)), 'EST') + self.assertRaises(TypeError, self.theclass, bytes([1] * len(base)), "EST") for ord_byte in range(1, 13): # This shouldn't blow up because of the month byte alone. If @@ -1392,12 +1411,15 @@ def test_backdoor_resistance(self): # blow up because other fields are insane. self.theclass(base[:2] + bytes([ord_byte]) + base[3:]) + ############################################################################# # datetime tests + class SubclassDatetime(datetime): sub_var = 1 + class TestDateTime(TestDate): theclass = datetime @@ -1425,62 +1447,64 @@ def test_basic_attributes_nonzero(self): self.assertEqual(dt.microsecond, 8000) def test_roundtrip(self): - for dt in (self.theclass(1, 2, 3, 4, 5, 6, 7), - self.theclass.now()): + for dt in (self.theclass(1, 2, 3, 4, 5, 6, 7), self.theclass.now()): # Verify dt -> string -> datetime identity. s = repr(dt) - self.assertTrue(s.startswith('datetime.')) + self.assertTrue(s.startswith("datetime.")) s = s[9:] dt2 = eval(s) self.assertEqual(dt, dt2) # Verify identity via reconstructing from pieces. - dt2 = self.theclass(dt.year, dt.month, dt.day, - dt.hour, dt.minute, dt.second, - dt.microsecond) + dt2 = self.theclass( + dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond + ) self.assertEqual(dt, dt2) def test_isoformat(self): t = self.theclass(2, 3, 2, 4, 5, 1, 123) - self.assertEqual(t.isoformat(), "0002-03-02T04:05:01.000123") - self.assertEqual(t.isoformat('T'), "0002-03-02T04:05:01.000123") - self.assertEqual(t.isoformat(' '), "0002-03-02 04:05:01.000123") - self.assertEqual(t.isoformat('\x00'), "0002-03-02\x0004:05:01.000123") + self.assertEqual(t.isoformat(), "0002-03-02T04:05:01.000123") + self.assertEqual(t.isoformat("T"), "0002-03-02T04:05:01.000123") + self.assertEqual(t.isoformat(" "), "0002-03-02 04:05:01.000123") + self.assertEqual(t.isoformat("\x00"), "0002-03-02\x0004:05:01.000123") # str is ISO format with the separator forced to a blank. self.assertEqual(str(t), "0002-03-02 04:05:01.000123") t = self.theclass(2, 3, 2) - self.assertEqual(t.isoformat(), "0002-03-02T00:00:00") - self.assertEqual(t.isoformat('T'), "0002-03-02T00:00:00") - self.assertEqual(t.isoformat(' '), "0002-03-02 00:00:00") + self.assertEqual(t.isoformat(), "0002-03-02T00:00:00") + self.assertEqual(t.isoformat("T"), "0002-03-02T00:00:00") + self.assertEqual(t.isoformat(" "), "0002-03-02 00:00:00") # str is ISO format with the separator forced to a blank. self.assertEqual(str(t), "0002-03-02 00:00:00") def test_format(self): dt = self.theclass(2007, 9, 10, 4, 5, 1, 123) - self.assertEqual(dt.__format__(''), str(dt)) + self.assertEqual(dt.__format__(""), str(dt)) # check that a derived class's __str__() gets called class A(self.theclass): def __str__(self): - return 'A' + return "A" + a = A(2007, 9, 10, 4, 5, 1, 123) - self.assertEqual(a.__format__(''), 'A') + self.assertEqual(a.__format__(""), "A") # check that a derived class's strftime gets called class B(self.theclass): def strftime(self, format_spec): - return 'B' + return "B" + b = B(2007, 9, 10, 4, 5, 1, 123) - self.assertEqual(b.__format__(''), str(dt)) + self.assertEqual(b.__format__(""), str(dt)) - for fmt in ["m:%m d:%d y:%y", - "m:%m d:%d y:%y H:%H M:%M S:%S", - "%z %Z", - ]: + for fmt in [ + "m:%m d:%d y:%y", + "m:%m d:%d y:%y H:%H M:%M S:%S", + "%z %Z", + ]: self.assertEqual(dt.__format__(fmt), dt.strftime(fmt)) self.assertEqual(a.__format__(fmt), dt.strftime(fmt)) - self.assertEqual(b.__format__(fmt), 'B') + self.assertEqual(b.__format__(fmt), "B") @unittest.skip("no time.ctime") def test_more_ctime(self): @@ -1524,25 +1548,27 @@ def tzname(self, dt): class MyStr(str): def replace(self, *args): return None - return MyStr('name') - t = self.theclass(2005, 3, 2, 0, 0, 0, 0, MyTzInfo(3, 'name')) - self.assertRaises(TypeError, t.strftime, '%Z') + + return MyStr("name") + + t = self.theclass(2005, 3, 2, 0, 0, 0, 0, MyTzInfo(3, "name")) + self.assertRaises(TypeError, t.strftime, "%Z") def test_bad_constructor_arguments(self): # bad years self.theclass(MINYEAR, 1, 1) # no exception self.theclass(MAXYEAR, 1, 1) # no exception - self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1) - self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1) + self.assertRaises(ValueError, self.theclass, MINYEAR - 1, 1, 1) + self.assertRaises(ValueError, self.theclass, MAXYEAR + 1, 1, 1) # bad months - self.theclass(2000, 1, 1) # no exception - self.theclass(2000, 12, 1) # no exception + self.theclass(2000, 1, 1) # no exception + self.theclass(2000, 12, 1) # no exception self.assertRaises(ValueError, self.theclass, 2000, 0, 1) self.assertRaises(ValueError, self.theclass, 2000, 13, 1) # bad days - self.theclass(2000, 2, 29) # no exception - self.theclass(2004, 2, 29) # no exception - self.theclass(2400, 2, 29) # no exception + self.theclass(2000, 2, 29) # no exception + self.theclass(2004, 2, 29) # no exception + self.theclass(2400, 2, 29) # no exception self.assertRaises(ValueError, self.theclass, 2000, 2, 30) self.assertRaises(ValueError, self.theclass, 2001, 2, 29) self.assertRaises(ValueError, self.theclass, 2100, 2, 29) @@ -1550,28 +1576,25 @@ def test_bad_constructor_arguments(self): self.assertRaises(ValueError, self.theclass, 2000, 1, 0) self.assertRaises(ValueError, self.theclass, 2000, 1, 32) # bad hours - self.theclass(2000, 1, 31, 0) # no exception - self.theclass(2000, 1, 31, 23) # no exception + self.theclass(2000, 1, 31, 0) # no exception + self.theclass(2000, 1, 31, 23) # no exception self.assertRaises(ValueError, self.theclass, 2000, 1, 31, -1) self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 24) # bad minutes - self.theclass(2000, 1, 31, 23, 0) # no exception - self.theclass(2000, 1, 31, 23, 59) # no exception + self.theclass(2000, 1, 31, 23, 0) # no exception + self.theclass(2000, 1, 31, 23, 59) # no exception self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, -1) self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 60) # bad seconds - self.theclass(2000, 1, 31, 23, 59, 0) # no exception - self.theclass(2000, 1, 31, 23, 59, 59) # no exception + self.theclass(2000, 1, 31, 23, 59, 0) # no exception + self.theclass(2000, 1, 31, 23, 59, 59) # no exception self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, -1) self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, 60) # bad microseconds - self.theclass(2000, 1, 31, 23, 59, 59, 0) # no exception - self.theclass(2000, 1, 31, 23, 59, 59, 999999) # no exception - self.assertRaises(ValueError, self.theclass, - 2000, 1, 31, 23, 59, 59, -1) - self.assertRaises(ValueError, self.theclass, - 2000, 1, 31, 23, 59, 59, - 1000000) + self.theclass(2000, 1, 31, 23, 59, 59, 0) # no exception + self.theclass(2000, 1, 31, 23, 59, 59, 999999) # no exception + self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, 59, -1) + self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, 59, 1000000) def test_hash_equality(self): d = self.theclass(2000, 12, 31, 23, 30, 17) @@ -1585,8 +1608,8 @@ def test_hash_equality(self): self.assertEqual(dic[d], 2) self.assertEqual(dic[e], 2) - d = self.theclass(2001, 1, 1, 0, 5, 17) - e = self.theclass(2001, 1, 1, 0, 5, 17) + d = self.theclass(2001, 1, 1, 0, 5, 17) + e = self.theclass(2001, 1, 1, 0, 5, 17) self.assertEqual(d, e) self.assertEqual(hash(d), hash(e)) @@ -1599,8 +1622,8 @@ def test_hash_equality(self): def test_computations(self): a = self.theclass(2002, 1, 31) b = self.theclass(1956, 1, 31) - diff = a-b - self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4))) + diff = a - b + self.assertEqual(diff.days, 46 * 365 + len(range(1956, 2002, 4))) self.assertEqual(diff.seconds, 0) self.assertEqual(diff.microseconds, 0) a = self.theclass(2002, 3, 2, 17, 6) @@ -1610,17 +1633,17 @@ def test_computations(self): week = timedelta(7) self.assertEqual(a + hour, self.theclass(2002, 3, 2, 18, 6)) self.assertEqual(hour + a, self.theclass(2002, 3, 2, 18, 6)) - self.assertEqual(a + 10*hour, self.theclass(2002, 3, 3, 3, 6)) + self.assertEqual(a + 10 * hour, self.theclass(2002, 3, 3, 3, 6)) self.assertEqual(a - hour, self.theclass(2002, 3, 2, 16, 6)) self.assertEqual(-hour + a, self.theclass(2002, 3, 2, 16, 6)) self.assertEqual(a - hour, a + -hour) - self.assertEqual(a - 20*hour, self.theclass(2002, 3, 1, 21, 6)) + self.assertEqual(a - 20 * hour, self.theclass(2002, 3, 1, 21, 6)) self.assertEqual(a + day, self.theclass(2002, 3, 3, 17, 6)) self.assertEqual(a - day, self.theclass(2002, 3, 1, 17, 6)) self.assertEqual(a + week, self.theclass(2002, 3, 9, 17, 6)) self.assertEqual(a - week, self.theclass(2002, 2, 23, 17, 6)) - self.assertEqual(a + 52*week, self.theclass(2003, 3, 1, 17, 6)) - self.assertEqual(a - 52*week, self.theclass(2001, 3, 3, 17, 6)) + self.assertEqual(a + 52 * week, self.theclass(2003, 3, 1, 17, 6)) + self.assertEqual(a - 52 * week, self.theclass(2001, 3, 3, 17, 6)) self.assertEqual((a + week) - a, week) self.assertEqual((a + day) - a, day) self.assertEqual((a + hour) - a, hour) @@ -1637,20 +1660,24 @@ def test_computations(self): self.assertEqual(a - (a - day), day) self.assertEqual(a - (a - hour), hour) self.assertEqual(a - (a - millisec), millisec) - self.assertEqual(a + (week + day + hour + millisec), - self.theclass(2002, 3, 10, 18, 6, 0, 1000)) - self.assertEqual(a + (week + day + hour + millisec), - (((a + week) + day) + hour) + millisec) - self.assertEqual(a - (week + day + hour + millisec), - self.theclass(2002, 2, 22, 16, 5, 59, 999000)) - self.assertEqual(a - (week + day + hour + millisec), - (((a - week) - day) - hour) - millisec) + self.assertEqual( + a + (week + day + hour + millisec), self.theclass(2002, 3, 10, 18, 6, 0, 1000) + ) + self.assertEqual( + a + (week + day + hour + millisec), (((a + week) + day) + hour) + millisec + ) + self.assertEqual( + a - (week + day + hour + millisec), self.theclass(2002, 2, 22, 16, 5, 59, 999000) + ) + self.assertEqual( + a - (week + day + hour + millisec), (((a - week) - day) - hour) - millisec + ) # Add/sub ints or floats should be illegal for i in 1, 1.0: - self.assertRaises(TypeError, lambda: a+i) - self.assertRaises(TypeError, lambda: a-i) - self.assertRaises(TypeError, lambda: i+a) - self.assertRaises(TypeError, lambda: i-a) + self.assertRaises(TypeError, lambda: a + i) + self.assertRaises(TypeError, lambda: a - i) + self.assertRaises(TypeError, lambda: i + a) + self.assertRaises(TypeError, lambda: i - a) # delta - datetime is senseless. self.assertRaises(TypeError, lambda: day - a) @@ -1665,7 +1692,7 @@ def test_computations(self): self.assertRaises(TypeError, lambda: a + a) def test_pickling(self): - args = 6, 7, 23, 20, 59, 1, 64**2 + args = 6, 7, 23, 20, 59, 1, 64 ** 2 orig = self.theclass(*args) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) @@ -1682,7 +1709,7 @@ def test_more_pickling(self): @unittest.skip("Skip pickling for MicroPython") def test_pickling_subclass_datetime(self): - args = 6, 7, 23, 20, 59, 1, 64**2 + args = 6, 7, 23, 20, 59, 1, 64 ** 2 orig = SubclassDatetime(*args) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) @@ -1706,7 +1733,7 @@ def test_more_compare(self): for i in range(len(args)): newargs = args[:] newargs[i] = args[i] + 1 - t2 = self.theclass(*newargs) # this is larger than t1 + t2 = self.theclass(*newargs) # this is larger than t1 self.assertTrue(t1 < t2) self.assertTrue(t2 > t1) self.assertTrue(t1 <= t2) @@ -1720,7 +1747,6 @@ def test_more_compare(self): self.assertTrue(not t1 >= t2) self.assertTrue(not t2 <= t1) - # A helper for timestamp constructor tests. def verify_field_equality(self, expected, got): self.assertEqual(expected.tm_year, got.year) @@ -1748,24 +1774,25 @@ def test_utcfromtimestamp(self): # Run with US-style DST rules: DST begins 2 a.m. on second Sunday in # March (M3.2.0) and ends 2 a.m. on first Sunday in November (M11.1.0). -# @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0') + # @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0') @unittest.skip("no support.run_with_tz") def test_timestamp_naive(self): t = self.theclass(1970, 1, 1) self.assertEqual(t.timestamp(), 18000.0) t = self.theclass(1970, 1, 1, 1, 2, 3, 4) - self.assertEqual(t.timestamp(), - 18000.0 + 3600 + 2*60 + 3 + 4*1e-6) + self.assertEqual(t.timestamp(), 18000.0 + 3600 + 2 * 60 + 3 + 4 * 1e-6) # Missing hour may produce platform-dependent result t = self.theclass(2012, 3, 11, 2, 30) - self.assertIn(self.theclass.fromtimestamp(t.timestamp()), - [t - timedelta(hours=1), t + timedelta(hours=1)]) + self.assertIn( + self.theclass.fromtimestamp(t.timestamp()), + [t - timedelta(hours=1), t + timedelta(hours=1)], + ) # Ambiguous hour defaults to DST t = self.theclass(2012, 11, 4, 1, 30) self.assertEqual(self.theclass.fromtimestamp(t.timestamp()), t) # Timestamp may raise an overflow error on some platforms - for t in [self.theclass(1,1,1), self.theclass(9999,12,12)]: + for t in [self.theclass(1, 1, 1), self.theclass(9999, 12, 12)]: try: s = t.timestamp() except OverflowError: @@ -1777,15 +1804,12 @@ def test_timestamp_aware(self): t = self.theclass(1970, 1, 1, tzinfo=timezone.utc) self.assertEqual(t.timestamp(), 0.0) t = self.theclass(1970, 1, 1, 1, 2, 3, 4, tzinfo=timezone.utc) - self.assertEqual(t.timestamp(), - 3600 + 2*60 + 3 + 4*1e-6) - t = self.theclass(1970, 1, 1, 1, 2, 3, 4, - tzinfo=timezone(timedelta(hours=-5), 'EST')) - self.assertEqual(t.timestamp(), - 18000 + 3600 + 2*60 + 3 + 4*1e-6) + self.assertEqual(t.timestamp(), 3600 + 2 * 60 + 3 + 4 * 1e-6) + t = self.theclass(1970, 1, 1, 1, 2, 3, 4, tzinfo=timezone(timedelta(hours=-5), "EST")) + self.assertEqual(t.timestamp(), 18000 + 3600 + 2 * 60 + 3 + 4 * 1e-6) + def test_microsecond_rounding(self): - for fts in [self.theclass.fromtimestamp, - self.theclass.utcfromtimestamp]: + for fts in [self.theclass.fromtimestamp, self.theclass.utcfromtimestamp]: zero = fts(0) self.assertEqual(zero.second, 0) self.assertEqual(zero.microsecond, 0) @@ -1823,8 +1847,7 @@ def test_insane_fromtimestamp(self): # exempt such platforms (provided they return reasonable # results!). for insane in -1e200, 1e200: - self.assertRaises(OverflowError, self.theclass.fromtimestamp, - insane) + self.assertRaises(OverflowError, self.theclass.fromtimestamp, insane) @unittest.skip("Skip pickling for MicroPython") def test_insane_utcfromtimestamp(self): @@ -1833,8 +1856,8 @@ def test_insane_utcfromtimestamp(self): # exempt such platforms (provided they return reasonable # results!). for insane in -1e200, 1e200: - self.assertRaises(OverflowError, self.theclass.utcfromtimestamp, - insane) + self.assertRaises(OverflowError, self.theclass.utcfromtimestamp, insane) + @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps") def test_negative_float_fromtimestamp(self): # The result is tz-dependent; at least test that this doesn't @@ -1862,8 +1885,8 @@ def test_utcnow(self): @unittest.skip("no _strptime module") def test_strptime(self): - string = '2004-12-01 13:02:47.197' - format = '%Y-%m-%d %H:%M:%S.%f' + string = "2004-12-01 13:02:47.197" + format = "%Y-%m-%d %H:%M:%S.%f" expected = _strptime._strptime_datetime(self.theclass, string, format) got = self.theclass.strptime(string, format) self.assertEqual(expected, got) @@ -1874,15 +1897,14 @@ def test_strptime(self): self.assertEqual(strptime("+0002", "%z").utcoffset(), 2 * MINUTE) self.assertEqual(strptime("-0002", "%z").utcoffset(), -2 * MINUTE) # Only local timezone and UTC are supported - for tzseconds, tzname in ((0, 'UTC'), (0, 'GMT'), - (-_time.timezone, _time.tzname[0])): + for tzseconds, tzname in ((0, "UTC"), (0, "GMT"), (-_time.timezone, _time.tzname[0])): if tzseconds < 0: - sign = '-' + sign = "-" seconds = -tzseconds else: - sign ='+' + sign = "+" seconds = tzseconds - hours, minutes = divmod(seconds//60, 60) + hours, minutes = divmod(seconds // 60, 60) dtstr = "{}{:02d}{:02d} {}".format(sign, hours, minutes, tzname) dt = strptime(dtstr, "%z %Z") self.assertEqual(dt.utcoffset(), timedelta(seconds=tzseconds)) @@ -1891,26 +1913,36 @@ def test_strptime(self): dtstr, fmt = "+1234 UTC", "%z %Z" dt = strptime(dtstr, fmt) self.assertEqual(dt.utcoffset(), 12 * HOUR + 34 * MINUTE) - self.assertEqual(dt.tzname(), 'UTC') + self.assertEqual(dt.tzname(), "UTC") # yet will roundtrip self.assertEqual(dt.strftime(fmt), dtstr) # Produce naive datetime if no %z is provided self.assertEqual(strptime("UTC", "%Z").tzinfo, None) - with self.assertRaises(ValueError): strptime("-2400", "%z") - with self.assertRaises(ValueError): strptime("-000", "%z") + with self.assertRaises(ValueError): + strptime("-2400", "%z") + with self.assertRaises(ValueError): + strptime("-000", "%z") def test_more_timetuple(self): # This tests fields beyond those tested by the TestDate.test_timetuple. t = self.theclass(2004, 12, 31, 6, 22, 33) self.assertEqual(t.timetuple(), (2004, 12, 31, 6, 22, 33, 4, 366, -1)) - self.assertEqual(t.timetuple(), - (t.year, t.month, t.day, - t.hour, t.minute, t.second, - t.weekday(), - t.toordinal() - date(t.year, 1, 1).toordinal() + 1, - -1)) + self.assertEqual( + t.timetuple(), + ( + t.year, + t.month, + t.day, + t.hour, + t.minute, + t.second, + t.weekday(), + t.toordinal() - date(t.year, 1, 1).toordinal() + 1, + -1, + ), + ) tt = t.timetuple() self.assertEqual(tt.tm_year, t.year) self.assertEqual(tt.tm_mon, t.month) @@ -1919,15 +1951,13 @@ def test_more_timetuple(self): self.assertEqual(tt.tm_min, t.minute) self.assertEqual(tt.tm_sec, t.second) self.assertEqual(tt.tm_wday, t.weekday()) - self.assertEqual(tt.tm_yday, t.toordinal() - - date(t.year, 1, 1).toordinal() + 1) + self.assertEqual(tt.tm_yday, t.toordinal() - date(t.year, 1, 1).toordinal() + 1) self.assertEqual(tt.tm_isdst, -1) def test_more_strftime(self): # This tests fields beyond those tested by the TestDate.test_strftime. t = self.theclass(2004, 12, 31, 6, 22, 33, 47) - self.assertEqual(t.strftime("%m %d %y %f %S %M %H %j"), - "12 31 04 000047 33 22 06 366") + self.assertEqual(t.strftime("%m %d %y %f %S %M %H %j"), "12 31 04 000047 33 22 06 366") def test_extract(self): dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234) @@ -1949,13 +1979,13 @@ def test_combine(self): self.assertEqual(t, dt.time()) self.assertEqual(dt, combine(dt.date(), dt.time())) - self.assertRaises(TypeError, combine) # need an arg - self.assertRaises(TypeError, combine, d) # need two args - self.assertRaises(TypeError, combine, t, d) # args reversed - self.assertRaises(TypeError, combine, d, t, 1) # too many args - self.assertRaises(TypeError, combine, "date", "time") # wrong types - self.assertRaises(TypeError, combine, d, "time") # wrong type - self.assertRaises(TypeError, combine, "date", t) # wrong type + self.assertRaises(TypeError, combine) # need an arg + self.assertRaises(TypeError, combine, d) # need two args + self.assertRaises(TypeError, combine, t, d) # args reversed + self.assertRaises(TypeError, combine, d, t, 1) # too many args + self.assertRaises(TypeError, combine, "date", "time") # wrong types + self.assertRaises(TypeError, combine, d, "time") # wrong type + self.assertRaises(TypeError, combine, "date", t) # wrong type def test_replace(self): cls = self.theclass @@ -1964,13 +1994,15 @@ def test_replace(self): self.assertEqual(base, base.replace()) i = 0 - for name, newval in (("year", 2), - ("month", 3), - ("day", 4), - ("hour", 5), - ("minute", 6), - ("second", 7), - ("microsecond", 8)): + for name, newval in ( + ("year", 2), + ("month", 3), + ("day", 4), + ("hour", 5), + ("minute", 6), + ("second", 7), + ("microsecond", 8), + ): newargs = args[:] newargs[i] = newval expected = cls(*newargs) @@ -1987,34 +2019,40 @@ def test_astimezone(self): # simply can't be applied to a naive object. dt = self.theclass.now() f = FixedOffset(44, "") - self.assertRaises(ValueError, dt.astimezone) # naive - self.assertRaises(TypeError, dt.astimezone, f, f) # too many args - self.assertRaises(TypeError, dt.astimezone, dt) # arg wrong type - self.assertRaises(ValueError, dt.astimezone, f) # naive + self.assertRaises(ValueError, dt.astimezone) # naive + self.assertRaises(TypeError, dt.astimezone, f, f) # too many args + self.assertRaises(TypeError, dt.astimezone, dt) # arg wrong type + self.assertRaises(ValueError, dt.astimezone, f) # naive self.assertRaises(ValueError, dt.astimezone, tz=f) # naive class Bogus(tzinfo): - def utcoffset(self, dt): return None - def dst(self, dt): return timedelta(0) + def utcoffset(self, dt): + return None + + def dst(self, dt): + return timedelta(0) + bog = Bogus() - self.assertRaises(ValueError, dt.astimezone, bog) # naive - self.assertRaises(ValueError, - dt.replace(tzinfo=bog).astimezone, f) + self.assertRaises(ValueError, dt.astimezone, bog) # naive + self.assertRaises(ValueError, dt.replace(tzinfo=bog).astimezone, f) class AlsoBogus(tzinfo): - def utcoffset(self, dt): return timedelta(0) - def dst(self, dt): return None + def utcoffset(self, dt): + return timedelta(0) + + def dst(self, dt): + return None + alsobog = AlsoBogus() - self.assertRaises(ValueError, dt.astimezone, alsobog) # also naive + self.assertRaises(ValueError, dt.astimezone, alsobog) # also naive def test_subclass_datetime(self): - class C(self.theclass): theAnswer = 42 def __new__(cls, *args, **kws): temp = kws.copy() - extra = temp.pop('extra') + extra = temp.pop("extra") result = self.theclass.__new__(cls, *args, **temp) result.extra = extra return result @@ -2025,14 +2063,14 @@ def newmeth(self, start): args = 2003, 4, 14, 12, 13, 41 dt1 = self.theclass(*args) - dt2 = C(*args, **{'extra': 7}) + dt2 = C(*args, **{"extra": 7}) self.assertEqual(dt2.__class__, C) self.assertEqual(dt2.theAnswer, 42) self.assertEqual(dt2.extra, 7) self.assertEqual(dt1.toordinal(), dt2.toordinal()) - self.assertEqual(dt2.newmeth(-7), dt1.year + dt1.month + - dt1.second - 7) + self.assertEqual(dt2.newmeth(-7), dt1.year + dt1.month + dt1.second - 7) + class TestSubclassDateTime(TestDateTime): theclass = SubclassDatetime @@ -2040,9 +2078,11 @@ class TestSubclassDateTime(TestDateTime): def test_roundtrip(self): pass + class SubclassTime(time): sub_var = 1 + class TestTime(HarmlessMixedComparison, unittest.TestCase): theclass = time @@ -2068,14 +2108,13 @@ def test_roundtrip(self): # Verify t -> string -> time identity. s = repr(t) - self.assertTrue(s.startswith('datetime.')) + self.assertTrue(s.startswith("datetime.")) s = s[9:] t2 = eval(s) self.assertEqual(t, t2) # Verify identity via reconstructing from pieces. - t2 = self.theclass(t.hour, t.minute, t.second, - t.microsecond) + t2 = self.theclass(t.hour, t.minute, t.second, t.microsecond) self.assertEqual(t, t2) def test_comparing(self): @@ -2092,7 +2131,7 @@ def test_comparing(self): for i in range(len(args)): newargs = args[:] newargs[i] = args[i] + 1 - t2 = self.theclass(*newargs) # this is larger than t1 + t2 = self.theclass(*newargs) # this is larger than t1 self.assertTrue(t1 < t2) self.assertTrue(t2 > t1) self.assertTrue(t1 <= t2) @@ -2123,23 +2162,23 @@ def test_comparing(self): def test_bad_constructor_arguments(self): # bad hours - self.theclass(0, 0) # no exception - self.theclass(23, 0) # no exception + self.theclass(0, 0) # no exception + self.theclass(23, 0) # no exception self.assertRaises(ValueError, self.theclass, -1, 0) self.assertRaises(ValueError, self.theclass, 24, 0) # bad minutes - self.theclass(23, 0) # no exception - self.theclass(23, 59) # no exception + self.theclass(23, 0) # no exception + self.theclass(23, 59) # no exception self.assertRaises(ValueError, self.theclass, 23, -1) self.assertRaises(ValueError, self.theclass, 23, 60) # bad seconds - self.theclass(23, 59, 0) # no exception - self.theclass(23, 59, 59) # no exception + self.theclass(23, 59, 0) # no exception + self.theclass(23, 59, 59) # no exception self.assertRaises(ValueError, self.theclass, 23, 59, -1) self.assertRaises(ValueError, self.theclass, 23, 59, 60) # bad microseconds - self.theclass(23, 59, 59, 0) # no exception - self.theclass(23, 59, 59, 999999) # no exception + self.theclass(23, 59, 59, 0) # no exception + self.theclass(23, 59, 59, 999999) # no exception self.assertRaises(ValueError, self.theclass, 23, 59, 59, -1) self.assertRaises(ValueError, self.theclass, 23, 59, 59, 1000000) @@ -2155,8 +2194,8 @@ def test_hash_equality(self): self.assertEqual(dic[d], 2) self.assertEqual(dic[e], 2) - d = self.theclass(0, 5, 17) - e = self.theclass(0, 5, 17) + d = self.theclass(0, 5, 17) + e = self.theclass(0, 5, 17) self.assertEqual(d, e) self.assertEqual(hash(d), hash(e)) @@ -2206,33 +2245,36 @@ def test_1653736(self): def test_strftime(self): t = self.theclass(1, 2, 3, 4) - self.assertEqual(t.strftime('%H %M %S %f'), "01 02 03 000004") + self.assertEqual(t.strftime("%H %M %S %f"), "01 02 03 000004") # A naive object replaces %z and %Z with empty strings. self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''") def test_format(self): t = self.theclass(1, 2, 3, 4) - self.assertEqual(t.__format__(''), str(t)) + self.assertEqual(t.__format__(""), str(t)) # check that a derived class's __str__() gets called class A(self.theclass): def __str__(self): - return 'A' + return "A" + a = A(1, 2, 3, 4) - self.assertEqual(a.__format__(''), 'A') + self.assertEqual(a.__format__(""), "A") # check that a derived class's strftime gets called class B(self.theclass): def strftime(self, format_spec): - return 'B' + return "B" + b = B(1, 2, 3, 4) - self.assertEqual(b.__format__(''), str(t)) + self.assertEqual(b.__format__(""), str(t)) - for fmt in ['%H %M %S', - ]: + for fmt in [ + "%H %M %S", + ]: self.assertEqual(t.__format__(fmt), t.strftime(fmt)) self.assertEqual(a.__format__(fmt), t.strftime(fmt)) - self.assertEqual(b.__format__(fmt), 'B') + self.assertEqual(b.__format__(fmt), "B") def test_str(self): self.assertEqual(str(self.theclass(1, 2, 3, 4)), "01:02:03.000004") @@ -2242,17 +2284,12 @@ def test_str(self): self.assertEqual(str(self.theclass(23, 15, 0, 0)), "23:15:00") def test_repr(self): - name = 'datetime.' + self.theclass.__name__ - self.assertEqual(repr(self.theclass(1, 2, 3, 4)), - "%s(1, 2, 3, 4)" % name) - self.assertEqual(repr(self.theclass(10, 2, 3, 4000)), - "%s(10, 2, 3, 4000)" % name) - self.assertEqual(repr(self.theclass(0, 2, 3, 400000)), - "%s(0, 2, 3, 400000)" % name) - self.assertEqual(repr(self.theclass(12, 2, 3, 0)), - "%s(12, 2, 3)" % name) - self.assertEqual(repr(self.theclass(23, 15, 0, 0)), - "%s(23, 15)" % name) + name = "datetime." + self.theclass.__name__ + self.assertEqual(repr(self.theclass(1, 2, 3, 4)), "%s(1, 2, 3, 4)" % name) + self.assertEqual(repr(self.theclass(10, 2, 3, 4000)), "%s(10, 2, 3, 4000)" % name) + self.assertEqual(repr(self.theclass(0, 2, 3, 400000)), "%s(0, 2, 3, 400000)" % name) + self.assertEqual(repr(self.theclass(12, 2, 3, 0)), "%s(12, 2, 3)" % name) + self.assertEqual(repr(self.theclass(23, 15, 0, 0)), "%s(23, 15)" % name) def test_resolution_info(self): self.assertIsInstance(self.theclass.min, self.theclass) @@ -2261,7 +2298,7 @@ def test_resolution_info(self): self.assertTrue(self.theclass.max > self.theclass.min) def test_pickling(self): - args = 20, 59, 16, 64**2 + args = 20, 59, 16, 64 ** 2 orig = self.theclass(*args) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) @@ -2270,7 +2307,7 @@ def test_pickling(self): @unittest.skip("Skip pickling for MicroPython") def test_pickling_subclass_time(self): - args = 20, 59, 16, 64**2 + args = 20, 59, 16, 64 ** 2 orig = SubclassTime(*args) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) @@ -2293,10 +2330,7 @@ def test_replace(self): self.assertEqual(base, base.replace()) i = 0 - for name, newval in (("hour", 5), - ("minute", 6), - ("second", 7), - ("microsecond", 8)): + for name, newval in (("hour", 5), ("minute", 6), ("second", 7), ("microsecond", 8)): newargs = args[:] newargs[i] = newval expected = cls(*newargs) @@ -2312,13 +2346,12 @@ def test_replace(self): self.assertRaises(ValueError, base.replace, microsecond=1000000) def test_subclass_time(self): - class C(self.theclass): theAnswer = 42 def __new__(cls, *args, **kws): temp = kws.copy() - extra = temp.pop('extra') + extra = temp.pop("extra") result = self.theclass.__new__(cls, *args, **temp) result.extra = extra return result @@ -2329,7 +2362,7 @@ def newmeth(self, start): args = 4, 5, 6 dt1 = self.theclass(*args) - dt2 = C(*args, **{'extra': 7}) + dt2 = C(*args, **{"extra": 7}) self.assertEqual(dt2.__class__, C) self.assertEqual(dt2.theAnswer, 42) @@ -2339,23 +2372,25 @@ def newmeth(self, start): def test_backdoor_resistance(self): # see TestDate.test_backdoor_resistance(). - base = '2:59.0' - for hour_byte in ' ', '9', chr(24), '\xff': - self.assertRaises(TypeError, self.theclass, - hour_byte + base[1:]) + base = "2:59.0" + for hour_byte in " ", "9", chr(24), "\xff": + self.assertRaises(TypeError, self.theclass, hour_byte + base[1:]) + # A mixin for classes with a tzinfo= argument. Subclasses must define # theclass as a class atribute, and theclass(1, 1, 1, tzinfo=whatever) # must be legit (which is true for time and datetime). class TZInfoBase: - def test_argument_passing(self): cls = self.theclass # A datetime passes itself on, a time passes None. class introspective(tzinfo): - def tzname(self, dt): return dt and "real" or "none" + def tzname(self, dt): + return dt and "real" or "none" + def utcoffset(self, dt): - return timedelta(minutes = dt and 42 or -42) + return timedelta(minutes=dt and 42 or -42) + dst = utcoffset obj = cls(1, 2, 3, tzinfo=introspective()) @@ -2372,13 +2407,21 @@ def test_bad_tzinfo_classes(self): self.assertRaises(TypeError, cls, 1, 1, 1, tzinfo=12) class NiceTry(object): - def __init__(self): pass - def utcoffset(self, dt): pass + def __init__(self): + pass + + def utcoffset(self, dt): + pass + self.assertRaises(TypeError, cls, 1, 1, 1, tzinfo=NiceTry) class BetterTry(tzinfo): - def __init__(self): pass - def utcoffset(self, dt): pass + def __init__(self): + pass + + def utcoffset(self, dt): + pass + b = BetterTry() t = cls(1, 1, 1, tzinfo=b) self.assertTrue(t.tzinfo is b) @@ -2387,14 +2430,12 @@ def test_utc_offset_out_of_bounds(self): class Edgy(tzinfo): def __init__(self, offset): self.offset = timedelta(minutes=offset) + def utcoffset(self, dt): return self.offset cls = self.theclass - for offset, legit in ((-1440, False), - (-1439, True), - (1439, True), - (1440, False)): + for offset, legit in ((-1440, False), (-1439, True), (1439, True), (1440, False)): if cls is time: t = cls(1, 2, 3, tzinfo=Edgy(offset)) elif cls is datetime: @@ -2404,7 +2445,7 @@ def utcoffset(self, dt): if legit: aofs = abs(offset) h, m = divmod(aofs, 60) - tag = "%c%02d:%02d" % (offset < 0 and '-' or '+', h, m) + tag = "%c%02d:%02d" % (offset < 0 and "-" or "+", h, m) if isinstance(t, datetime): t = t.timetz() self.assertEqual(str(t), "01:02:03" + tag) @@ -2413,21 +2454,32 @@ def utcoffset(self, dt): def test_tzinfo_classes(self): cls = self.theclass + class C1(tzinfo): - def utcoffset(self, dt): return None - def dst(self, dt): return None - def tzname(self, dt): return None - for t in (cls(1, 1, 1), - cls(1, 1, 1, tzinfo=None), - cls(1, 1, 1, tzinfo=C1())): + def utcoffset(self, dt): + return None + + def dst(self, dt): + return None + + def tzname(self, dt): + return None + + for t in (cls(1, 1, 1), cls(1, 1, 1, tzinfo=None), cls(1, 1, 1, tzinfo=C1())): self.assertTrue(t.utcoffset() is None) self.assertTrue(t.dst() is None) self.assertTrue(t.tzname() is None) class C3(tzinfo): - def utcoffset(self, dt): return timedelta(minutes=-1439) - def dst(self, dt): return timedelta(minutes=1439) - def tzname(self, dt): return "aname" + def utcoffset(self, dt): + return timedelta(minutes=-1439) + + def dst(self, dt): + return timedelta(minutes=1439) + + def tzname(self, dt): + return "aname" + t = cls(1, 1, 1, tzinfo=C3()) self.assertEqual(t.utcoffset(), timedelta(minutes=-1439)) self.assertEqual(t.dst(), timedelta(minutes=1439)) @@ -2435,9 +2487,15 @@ def tzname(self, dt): return "aname" # Wrong types. class C4(tzinfo): - def utcoffset(self, dt): return "aname" - def dst(self, dt): return 7 - def tzname(self, dt): return 0 + def utcoffset(self, dt): + return "aname" + + def dst(self, dt): + return 7 + + def tzname(self, dt): + return 0 + t = cls(1, 1, 1, tzinfo=C4()) self.assertRaises(TypeError, t.utcoffset) self.assertRaises(TypeError, t.dst) @@ -2445,16 +2503,24 @@ def tzname(self, dt): return 0 # Offset out of range. class C6(tzinfo): - def utcoffset(self, dt): return timedelta(hours=-24) - def dst(self, dt): return timedelta(hours=24) + def utcoffset(self, dt): + return timedelta(hours=-24) + + def dst(self, dt): + return timedelta(hours=24) + t = cls(1, 1, 1, tzinfo=C6()) self.assertRaises(ValueError, t.utcoffset) self.assertRaises(ValueError, t.dst) # Not a whole number of minutes. class C7(tzinfo): - def utcoffset(self, dt): return timedelta(seconds=61) - def dst(self, dt): return timedelta(microseconds=-81) + def utcoffset(self, dt): + return timedelta(seconds=61) + + def dst(self, dt): + return timedelta(microseconds=-81) + t = cls(1, 1, 1, tzinfo=C7()) self.assertRaises(ValueError, t.utcoffset) self.assertRaises(ValueError, t.dst) @@ -2523,7 +2589,7 @@ def test_zones(self): est = FixedOffset(-300, "EST", 1) utc = FixedOffset(0, "UTC", -2) met = FixedOffset(60, "MET", 3) - t1 = time( 7, 47, tzinfo=est) + t1 = time(7, 47, tzinfo=est) t2 = time(12, 47, tzinfo=utc) t3 = time(13, 47, tzinfo=met) t4 = time(microsecond=40) @@ -2560,9 +2626,9 @@ def test_zones(self): self.assertEqual(t1, t2) self.assertEqual(t1, t3) self.assertEqual(t2, t3) - self.assertNotEqual(t4, t5) # mixed tz-aware & naive - self.assertRaises(TypeError, lambda: t4 < t5) # mixed tz-aware & naive - self.assertRaises(TypeError, lambda: t5 < t4) # mixed tz-aware & naive + self.assertNotEqual(t4, t5) # mixed tz-aware & naive + self.assertRaises(TypeError, lambda: t4 < t5) # mixed tz-aware & naive + self.assertRaises(TypeError, lambda: t5 < t4) # mixed tz-aware & naive self.assertEqual(str(t1), "07:47:00-05:00") self.assertEqual(str(t2), "12:47:00+00:00") @@ -2576,34 +2642,36 @@ def test_zones(self): self.assertEqual(t4.isoformat(), "00:00:00.000040") self.assertEqual(t5.isoformat(), "00:00:00.000040+00:00") - d = 'datetime.time' + d = "datetime.time" self.assertEqual(repr(t1), d + "(7, 47, tzinfo=est)") self.assertEqual(repr(t2), d + "(12, 47, tzinfo=utc)") self.assertEqual(repr(t3), d + "(13, 47, tzinfo=met)") self.assertEqual(repr(t4), d + "(0, 0, 0, 40)") self.assertEqual(repr(t5), d + "(0, 0, 0, 40, tzinfo=utc)") - self.assertEqual(t1.strftime("%H:%M:%S %%Z=%Z %%z=%z"), - "07:47:00 %Z=EST %z=-0500") + self.assertEqual(t1.strftime("%H:%M:%S %%Z=%Z %%z=%z"), "07:47:00 %Z=EST %z=-0500") self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000") self.assertEqual(t3.strftime("%H:%M:%S %Z %z"), "13:47:00 MET +0100") yuck = FixedOffset(-1439, "%z %Z %%z%%Z") t1 = time(23, 59, tzinfo=yuck) -# self.assertEqual(t1.strftime("%H:%M %%Z='%Z' %%z='%z'"), -# "23:59 %Z='%z %Z %%z%%Z' %z='-2359'") + # self.assertEqual(t1.strftime("%H:%M %%Z='%Z' %%z='%z'"), + # "23:59 %Z='%z %Z %%z%%Z' %z='-2359'") # Check that an invalid tzname result raises an exception. class Badtzname(tzinfo): tz = 42 - def tzname(self, dt): return self.tz + + def tzname(self, dt): + return self.tz + t = time(2, 3, 4, tzinfo=Badtzname()) self.assertEqual(t.strftime("%H:%M:%S"), "02:03:04") self.assertRaises(TypeError, t.strftime, "%Z") # Issue #6697: - if '_Fast' in str(type(self)): - Badtzname.tz = '\ud800' + if "_Fast" in str(type(self)): + Badtzname.tz = "\ud800" self.assertRaises(ValueError, t.strftime, "%Z") def test_hash_edge_cases(self): @@ -2618,7 +2686,7 @@ def test_hash_edge_cases(self): def test_pickling(self): # Try one without a tzinfo. - args = 20, 59, 16, 64**2 + args = 20, 59, 16, 64 ** 2 orig = self.theclass(*args) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) @@ -2627,7 +2695,7 @@ def test_pickling(self): def _test_pickling2(self): # Try one with a tzinfo. - tinfo = PicklableFixedOffset(-300, 'cookie') + tinfo = PicklableFixedOffset(-300, "cookie") orig = self.theclass(5, 6, 7, tzinfo=tinfo) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) @@ -2635,7 +2703,7 @@ def _test_pickling2(self): self.assertEqual(orig, derived) self.assertIsInstance(derived.tzinfo, PicklableFixedOffset) self.assertEqual(derived.utcoffset(), timedelta(minutes=-300)) - self.assertEqual(derived.tzname(), 'cookie') + self.assertEqual(derived.tzname(), "cookie") def test_more_bool(self): # Test cases with non-None tzinfo. @@ -2650,19 +2718,19 @@ def test_more_bool(self): t = cls(5, tzinfo=FixedOffset(300, "")) self.assertTrue(not t) - t = cls(23, 59, tzinfo=FixedOffset(23*60 + 59, "")) + t = cls(23, 59, tzinfo=FixedOffset(23 * 60 + 59, "")) self.assertTrue(not t) # Mostly ensuring this doesn't overflow internally. - t = cls(0, tzinfo=FixedOffset(23*60 + 59, "")) + t = cls(0, tzinfo=FixedOffset(23 * 60 + 59, "")) self.assertTrue(t) # But this should yield a value error -- the utcoffset is bogus. - t = cls(0, tzinfo=FixedOffset(24*60, "")) + t = cls(0, tzinfo=FixedOffset(24 * 60, "")) self.assertRaises(ValueError, lambda: bool(t)) # Likewise. - t = cls(0, tzinfo=FixedOffset(-24*60, "")) + t = cls(0, tzinfo=FixedOffset(-24 * 60, "")) self.assertRaises(ValueError, lambda: bool(t)) def test_replace(self): @@ -2674,11 +2742,13 @@ def test_replace(self): self.assertEqual(base, base.replace()) i = 0 - for name, newval in (("hour", 5), - ("minute", 6), - ("second", 7), - ("microsecond", 8), - ("tzinfo", zm200)): + for name, newval in ( + ("hour", 5), + ("minute", 6), + ("second", 7), + ("microsecond", 8), + ("tzinfo", zm200), + ): newargs = args[:] newargs[i] = newval expected = cls(*newargs) @@ -2719,6 +2789,7 @@ def test_mixed_compare(self): class Varies(tzinfo): def __init__(self): self.offset = timedelta(minutes=22) + def utcoffset(self, t): self.offset += timedelta(minutes=1) return self.offset @@ -2735,13 +2806,12 @@ def utcoffset(self, t): self.assertTrue(t1 < t2) # t1's offset counter still going up def test_subclass_timetz(self): - class C(self.theclass): theAnswer = 42 def __new__(cls, *args, **kws): temp = kws.copy() - extra = temp.pop('extra') + extra = temp.pop("extra") result = self.theclass.__new__(cls, *args, **temp) result.extra = extra return result @@ -2752,7 +2822,7 @@ def newmeth(self, start): args = 4, 5, 6, 500, FixedOffset(-300, "EST", 1) dt1 = self.theclass(*args) - dt2 = C(*args, **{'extra': 7}) + dt2 = C(*args, **{"extra": 7}) self.assertEqual(dt2.__class__, C) self.assertEqual(dt2.theAnswer, 42) @@ -2763,6 +2833,7 @@ def newmeth(self, start): # Testing datetime objects with a non-None tzinfo. + class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): theclass = datetime @@ -2784,8 +2855,7 @@ def test_even_more_compare(self): # Smallest possible after UTC adjustment. t1 = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "")) # Largest possible after UTC adjustment. - t2 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999, - tzinfo=FixedOffset(-1439, "")) + t2 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=FixedOffset(-1439, "")) # Make sure those compare correctly, and w/o overflow. self.assertTrue(t1 < t2) @@ -2797,7 +2867,7 @@ def test_even_more_compare(self): # Equal afer adjustment. t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, "")) - t2 = self.theclass(2, 1, 1, 3, 13, tzinfo=FixedOffset(3*60+13+2, "")) + t2 = self.theclass(2, 1, 1, 3, 13, tzinfo=FixedOffset(3 * 60 + 13 + 2, "")) self.assertEqual(t1, t2) # Change t1 not to subtract a minute, and t1 should be larger. @@ -2809,13 +2879,11 @@ def test_even_more_compare(self): self.assertTrue(t1 < t2) # Back to the original t1, but make seconds resolve it. - t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""), - second=1) + t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""), second=1) self.assertTrue(t1 > t2) # Likewise, but make microseconds resolve it. - t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""), - microsecond=1) + t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""), microsecond=1) self.assertTrue(t1 > t2) # Make t2 naive and it should differ. @@ -2825,7 +2893,9 @@ def test_even_more_compare(self): # It's also naive if it has tzinfo but tzinfo.utcoffset() is None. class Naive(tzinfo): - def utcoffset(self, dt): return None + def utcoffset(self, dt): + return None + t2 = self.theclass(5, 6, 7, tzinfo=Naive()) self.assertNotEqual(t1, t2) self.assertEqual(t2, t2) @@ -2838,14 +2908,15 @@ def utcoffset(self, dt): return None # Try a bogus uctoffset. class Bogus(tzinfo): def utcoffset(self, dt): - return timedelta(minutes=1440) # out of bounds + return timedelta(minutes=1440) # out of bounds + t1 = self.theclass(2, 2, 2, tzinfo=Bogus()) t2 = self.theclass(2, 2, 2, tzinfo=FixedOffset(0, "")) self.assertRaises(ValueError, lambda: t1 == t2) def test_pickling(self): # Try one without a tzinfo. - args = 6, 7, 23, 20, 59, 1, 64**2 + args = 6, 7, 23, 20, 59, 1, 64 ** 2 orig = self.theclass(*args) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) @@ -2854,8 +2925,8 @@ def test_pickling(self): def _test_pickling2(self): # Try one with a tzinfo. - tinfo = PicklableFixedOffset(-300, 'cookie') - orig = self.theclass(*args, **{'tzinfo': tinfo}) + tinfo = PicklableFixedOffset(-300, "cookie") + orig = self.theclass(*args, **{"tzinfo": tinfo}) derived = self.theclass(1, 1, 1, tzinfo=FixedOffset(0, "", 0)) for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) @@ -2863,7 +2934,7 @@ def _test_pickling2(self): self.assertEqual(orig, derived) self.assertIsInstance(derived.tzinfo, PicklableFixedOffset) self.assertEqual(derived.utcoffset(), timedelta(minutes=-300)) - self.assertEqual(derived.tzname(), 'cookie') + self.assertEqual(derived.tzname(), "cookie") def test_extreme_hashes(self): # If an attempt is made to hash these via subtracting the offset @@ -2871,8 +2942,7 @@ def test_extreme_hashes(self): # Python implementation used to blow up here. t = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "")) hash(t) - t = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999, - tzinfo=FixedOffset(-1439, "")) + t = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=FixedOffset(-1439, "")) hash(t) # OTOH, an OOB offset should blow up. @@ -2883,7 +2953,7 @@ def test_zones(self): est = FixedOffset(-300, "EST") utc = FixedOffset(0, "UTC") met = FixedOffset(60, "MET") - t1 = datetime(2002, 3, 19, 7, 47, tzinfo=est) + t1 = datetime(2002, 3, 19, 7, 47, tzinfo=est) t2 = datetime(2002, 3, 19, 12, 47, tzinfo=utc) t3 = datetime(2002, 3, 19, 13, 47, tzinfo=met) self.assertEqual(t1.tzinfo, est) @@ -2904,7 +2974,7 @@ def test_zones(self): self.assertEqual(str(t1), "2002-03-19 07:47:00-05:00") self.assertEqual(str(t2), "2002-03-19 12:47:00+00:00") self.assertEqual(str(t3), "2002-03-19 13:47:00+01:00") - d = 'datetime.datetime(2002, 3, 19, ' + d = "datetime.datetime(2002, 3, 19, " self.assertEqual(repr(t1), d + "7, 47, tzinfo=est)") self.assertEqual(repr(t2), d + "12, 47, tzinfo=utc)") self.assertEqual(repr(t3), d + "13, 47, tzinfo=met)") @@ -2914,8 +2984,7 @@ def test_combine(self): d = date(2002, 3, 4) tz = time(18, 45, 3, 1234, tzinfo=met) dt = datetime.combine(d, tz) - self.assertEqual(dt, datetime(2002, 3, 4, 18, 45, 3, 1234, - tzinfo=met)) + self.assertEqual(dt, datetime(2002, 3, 4, 18, 45, 3, 1234, tzinfo=met)) def test_extract(self): met = FixedOffset(60, "MET") @@ -2980,14 +3049,14 @@ def test_tz_aware_arithmetic(self): # Try max possible difference. min = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "min")) - max = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999, - tzinfo=FixedOffset(-1439, "max")) + max = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=FixedOffset(-1439, "max")) maxdiff = max - min - self.assertEqual(maxdiff, self.theclass.max - self.theclass.min + - timedelta(minutes=2*1439)) + self.assertEqual( + maxdiff, self.theclass.max - self.theclass.min + timedelta(minutes=2 * 1439) + ) # Different tzinfo, but the same offset - tza = timezone(HOUR, 'A') - tzb = timezone(HOUR, 'B') + tza = timezone(HOUR, "A") + tzb = timezone(HOUR, "B") delta = min.replace(tzinfo=tza) - max.replace(tzinfo=tzb) self.assertEqual(delta, self.theclass.min - self.theclass.max) @@ -3013,8 +3082,10 @@ def test_tzinfo_now(self): # class to represent it, so seeing whether a tz argument actually # does a conversion is tricky. utc = FixedOffset(0, "utc", 0) - for weirdtz in [FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0), - timezone(timedelta(hours=15, minutes=58), "weirdtz"),]: + for weirdtz in [ + FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0), + timezone(timedelta(hours=15, minutes=58), "weirdtz"), + ]: for dummy in range(3): now = datetime.now(weirdtz) self.assertTrue(now.tzinfo is weirdtz) @@ -3030,6 +3101,7 @@ def test_tzinfo_now(self): def test_tzinfo_fromtimestamp(self): import time + meth = self.theclass.fromtimestamp ts = time.time() # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up). @@ -3057,7 +3129,7 @@ def test_tzinfo_fromtimestamp(self): # But on some flavor of Mac, it's nowhere near that. So we can't have # any idea here what time that actually is, we can only test that # relative changes match. - utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero + utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero tz = FixedOffset(utcoffset, "tz", 0) expected = utcdatetime + utcoffset got = datetime.fromtimestamp(timestamp, tz) @@ -3075,6 +3147,7 @@ def test_tzinfo_utcnow(self): def test_tzinfo_utcfromtimestamp(self): import time + meth = self.theclass.utcfromtimestamp ts = time.time() # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up). @@ -3093,6 +3166,7 @@ def __init__(self, dstvalue): if isinstance(dstvalue, int): dstvalue = timedelta(minutes=dstvalue) self.dstvalue = dstvalue + def dst(self, dt): return self.dstvalue @@ -3114,12 +3188,12 @@ def dst(self, dt): self.assertRaises(TypeError, cls(1, 1, 1, tzinfo=DST("x")).timetuple) # dst() at the edge. - self.assertEqual(cls(1,1,1, tzinfo=DST(1439)).timetuple().tm_isdst, 1) - self.assertEqual(cls(1,1,1, tzinfo=DST(-1439)).timetuple().tm_isdst, 1) + self.assertEqual(cls(1, 1, 1, tzinfo=DST(1439)).timetuple().tm_isdst, 1) + self.assertEqual(cls(1, 1, 1, tzinfo=DST(-1439)).timetuple().tm_isdst, 1) # dst() out of range. - self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(1440)).timetuple) - self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(-1440)).timetuple) + self.assertRaises(ValueError, cls(1, 1, 1, tzinfo=DST(1440)).timetuple) + self.assertRaises(ValueError, cls(1, 1, 1, tzinfo=DST(-1440)).timetuple) def test_utctimetuple(self): class DST(tzinfo): @@ -3127,18 +3201,19 @@ def __init__(self, dstvalue=0): if isinstance(dstvalue, int): dstvalue = timedelta(minutes=dstvalue) self.dstvalue = dstvalue + def dst(self, dt): return self.dstvalue cls = self.theclass # This can't work: DST didn't implement utcoffset. - self.assertRaises(NotImplementedError, - cls(1, 1, 1, tzinfo=DST(0)).utcoffset) + self.assertRaises(NotImplementedError, cls(1, 1, 1, tzinfo=DST(0)).utcoffset) class UOFS(DST): def __init__(self, uofs, dofs=None): DST.__init__(self, dofs) self.uofs = timedelta(minutes=uofs) + def utcoffset(self, dt): return self.uofs @@ -3148,12 +3223,11 @@ def utcoffset(self, dt): self.assertEqual(d.year, t.tm_year) self.assertEqual(d.month, t.tm_mon) self.assertEqual(d.day, t.tm_mday) - self.assertEqual(11, t.tm_hour) # 20mm + 53mm = 1hn + 13mm + self.assertEqual(11, t.tm_hour) # 20mm + 53mm = 1hn + 13mm self.assertEqual(13, t.tm_min) self.assertEqual(d.second, t.tm_sec) self.assertEqual(d.weekday(), t.tm_wday) - self.assertEqual(d.toordinal() - date(1, 1, 1).toordinal() + 1, - t.tm_yday) + self.assertEqual(d.toordinal() - date(1, 1, 1).toordinal() + 1, t.tm_yday) # Ensure tm_isdst is 0 regardless of what dst() says: DST # is never in effect for a UTC time. self.assertEqual(0, t.tm_isdst) @@ -3167,6 +3241,7 @@ def utcoffset(self, dt): class NOFS(DST): def utcoffset(self, dt): return None + d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=NOFS()) t = d.utctimetuple() self.assertEqual(t[:-1], d.timetuple()[:-1]) @@ -3175,6 +3250,7 @@ def utcoffset(self, dt): class BOFS(DST): def utcoffset(self, dt): return "EST" + d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=BOFS()) self.assertRaises(TypeError, d.utctimetuple) @@ -3183,8 +3259,9 @@ def utcoffset(self, dt): d = cls(2010, 11, 13, 14, 15, 16, 171819) for tz in [timezone.min, timezone.utc, timezone.max]: dtz = d.replace(tzinfo=tz) - self.assertEqual(dtz.utctimetuple()[:-1], - dtz.astimezone(timezone.utc).timetuple()[:-1]) + self.assertEqual( + dtz.utctimetuple()[:-1], dtz.astimezone(timezone.utc).timetuple()[:-1] + ) # At the edges, UTC adjustment can produce years out-of-range # for a datetime object. Ensure that an OverflowError is # raised. @@ -3208,19 +3285,19 @@ def test_tzinfo_isoformat(self): unknown = FixedOffset(None, "") cls = self.theclass - datestr = '0001-02-03' + datestr = "0001-02-03" for ofs in None, zero, plus, minus, unknown: for us in 0, 987001: d = cls(1, 2, 3, 4, 5, 59, us, tzinfo=ofs) - timestr = '04:05:59' + (us and '.987001' or '') - ofsstr = ofs is not None and d.tzname() or '' + timestr = "04:05:59" + (us and ".987001" or "") + ofsstr = ofs is not None and d.tzname() or "" tailstr = timestr + ofsstr iso = d.isoformat() - self.assertEqual(iso, datestr + 'T' + tailstr) - self.assertEqual(iso, d.isoformat('T')) - self.assertEqual(d.isoformat('k'), datestr + 'k' + tailstr) - self.assertEqual(d.isoformat('\u1234'), datestr + '\u1234' + tailstr) - self.assertEqual(str(d), datestr + ' ' + tailstr) + self.assertEqual(iso, datestr + "T" + tailstr) + self.assertEqual(iso, d.isoformat("T")) + self.assertEqual(d.isoformat("k"), datestr + "k" + tailstr) + self.assertEqual(d.isoformat("\u1234"), datestr + "\u1234" + tailstr) + self.assertEqual(str(d), datestr + " " + tailstr) def test_replace(self): cls = self.theclass @@ -3231,14 +3308,16 @@ def test_replace(self): self.assertEqual(base, base.replace()) i = 0 - for name, newval in (("year", 2), - ("month", 3), - ("day", 4), - ("hour", 5), - ("minute", 6), - ("second", 7), - ("microsecond", 8), - ("tzinfo", zm200)): + for name, newval in ( + ("year", 2), + ("month", 3), + ("day", 4), + ("hour", 5), + ("minute", 6), + ("second", 7), + ("microsecond", 8), + ("tzinfo", zm200), + ): newargs = args[:] newargs[i] = newval expected = cls(*newargs) @@ -3283,14 +3362,14 @@ def test_more_astimezone(self): self.assertEqual(got.utcoffset(), timedelta(hours=-5)) expected = dt - dt.utcoffset() # in effect, convert to UTC expected += fm5h.utcoffset(dt) # and from there to local time - expected = expected.replace(tzinfo=fm5h) # and attach new tzinfo + expected = expected.replace(tzinfo=fm5h) # and attach new tzinfo self.assertEqual(got.date(), expected.date()) self.assertEqual(got.time(), expected.time()) self.assertEqual(got.timetz(), expected.timetz()) self.assertTrue(got.tzinfo is expected.tzinfo) self.assertEqual(got, expected) -# @support.run_with_tz('UTC') + # @support.run_with_tz('UTC') def test_astimezone_default_utc(self): dt = self.theclass.now(timezone.utc) self.assertEqual(dt.astimezone(None), dt) @@ -3298,7 +3377,7 @@ def test_astimezone_default_utc(self): # Note that offset in TZ variable has the opposite sign to that # produced by %z directive. -# @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0') + # @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0') @unittest.skip("no support.run_with_tz") def test_astimezone_default_eastern(self): dt = self.theclass(2012, 11, 4, 6, 30, tzinfo=timezone.utc) @@ -3348,10 +3427,10 @@ def utcoffset(self, t): elif x is y is d2: expected = timedelta(0) elif x is d2: - expected = timedelta(minutes=(11-59)-0) + expected = timedelta(minutes=(11 - 59) - 0) else: assert y is d2 - expected = timedelta(minutes=0-(11-59)) + expected = timedelta(minutes=0 - (11 - 59)) self.assertEqual(got, expected) def test_mixed_compare(self): @@ -3369,6 +3448,7 @@ def test_mixed_compare(self): class Varies(tzinfo): def __init__(self): self.offset = timedelta(minutes=22) + def utcoffset(self, t): self.offset += timedelta(minutes=1) return self.offset @@ -3385,13 +3465,12 @@ def utcoffset(self, t): self.assertTrue(t1 < t2) # t1's offset counter still going up def test_subclass_datetimetz(self): - class C(self.theclass): theAnswer = 42 def __new__(cls, *args, **kws): temp = kws.copy() - extra = temp.pop('extra') + extra = temp.pop("extra") result = self.theclass.__new__(cls, *args, **temp) result.extra = extra return result @@ -3402,7 +3481,7 @@ def newmeth(self, start): args = 2002, 12, 31, 4, 5, 6, 500, FixedOffset(-300, "EST", 1) dt1 = self.theclass(*args) - dt2 = C(*args, **{'extra': 7}) + dt2 = C(*args, **{"extra": 7}) self.assertEqual(dt2.__class__, C) self.assertEqual(dt2.theAnswer, 42) @@ -3410,14 +3489,17 @@ def newmeth(self, start): self.assertEqual(dt1.utcoffset(), dt2.utcoffset()) self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.year - 7) + # Pain to set up DST-aware tzinfo classes. + def first_sunday_on_or_after(dt): days_to_go = 6 - dt.weekday() if days_to_go: dt += timedelta(days_to_go) return dt + ZERO = timedelta(0) MINUTE = timedelta(minutes=1) HOUR = timedelta(hours=1) @@ -3430,8 +3512,8 @@ def first_sunday_on_or_after(dt): # the last hour of DST (that's 1:MM DST, but 1:MM is taken as standard time). DSTEND = datetime(1, 10, 25, 1) -class USTimeZone(tzinfo): +class USTimeZone(tzinfo): def __init__(self, hours, reprname, stdname, dstname): self.stdoffset = timedelta(hours=hours) self.reprname = reprname @@ -3472,14 +3554,16 @@ def dst(self, dt): else: return ZERO -Eastern = USTimeZone(-5, "Eastern", "EST", "EDT") -Central = USTimeZone(-6, "Central", "CST", "CDT") + +Eastern = USTimeZone(-5, "Eastern", "EST", "EDT") +Central = USTimeZone(-6, "Central", "CST", "CDT") Mountain = USTimeZone(-7, "Mountain", "MST", "MDT") -Pacific = USTimeZone(-8, "Pacific", "PST", "PDT") +Pacific = USTimeZone(-8, "Pacific", "PST", "PDT") utc_real = FixedOffset(0, "UTC", 0) # For better test coverage, we want another flavor of UTC that's west of # the Eastern and Pacific timezones. -utc_fake = FixedOffset(-12*60, "UTCfake", 0) +utc_fake = FixedOffset(-12 * 60, "UTCfake", 0) + class TestTimezoneConversions(unittest.TestCase): # The DST switch times for 2002, in std time. @@ -3514,8 +3598,7 @@ def checkinside(self, dt, tz, utc, dston, dstoff): # time, there_and_back is not. self.assertEqual(there_and_back.dst(), ZERO) # They're the same times in UTC. - self.assertEqual(there_and_back.astimezone(utc), - dt.astimezone(utc)) + self.assertEqual(there_and_back.astimezone(utc), dt.astimezone(utc)) else: # We're not in the redundant hour. self.assertEqual(dt, there_and_back) @@ -3560,11 +3643,13 @@ def convert_between_tz_and_utc(self, tz, utc): # taken as being daylight time (and 1:MM is taken as being standard # time). dstoff = self.dstoff.replace(tzinfo=tz) - for delta in (timedelta(weeks=13), - DAY, - HOUR, - timedelta(minutes=1), - timedelta(microseconds=1)): + for delta in ( + timedelta(weeks=13), + DAY, + HOUR, + timedelta(minutes=1), + timedelta(microseconds=1), + ): self.checkinside(dston, tz, utc, dston, dstoff) for during in dston + delta, dstoff - delta: @@ -3601,7 +3686,7 @@ def test_easy(self): def test_tricky(self): # 22:00 on day before daylight starts. fourback = self.dston - timedelta(hours=4) - ninewest = FixedOffset(-9*60, "-0900", 0) + ninewest = FixedOffset(-9 * 60, "-0900", 0) fourback = fourback.replace(tzinfo=ninewest) # 22:00-0900 is 7:00 UTC == 2:00 EST == 3:00 DST. Since it's "after # 2", we should get the 3 spelling. @@ -3631,7 +3716,7 @@ def test_tricky(self): # wall 0:MM 1:MM 1:MM 2:MM against these for utc in utc_real, utc_fake: for tz in Eastern, Pacific: - first_std_hour = self.dstoff - timedelta(hours=2) # 23:MM + first_std_hour = self.dstoff - timedelta(hours=2) # 23:MM # Convert that to UTC. first_std_hour -= tz.utcoffset(None) # Adjust for possibly fake UTC. @@ -3648,11 +3733,13 @@ def test_tricky(self): self.assertEqual(astz.replace(tzinfo=None), expected) asutcbase += HOUR - def test_bogus_dst(self): class ok(tzinfo): - def utcoffset(self, dt): return HOUR - def dst(self, dt): return HOUR + def utcoffset(self, dt): + return HOUR + + def dst(self, dt): + return HOUR now = self.theclass.now().replace(tzinfo=utc_real) # Doesn't blow up. @@ -3660,7 +3747,9 @@ def dst(self, dt): return HOUR # Does blow up. class notok(ok): - def dst(self, dt): return None + def dst(self, dt): + return None + self.assertRaises(ValueError, now.astimezone, notok()) # Sometimes blow up. In the following, tzinfo.dst() @@ -3672,25 +3761,27 @@ def dst(self, dt): if dt.year == 2000: return None else: - return 10*HOUR + return 10 * HOUR + dt = self.theclass(2001, 1, 1).replace(tzinfo=utc_real) self.assertRaises(ValueError, dt.astimezone, tricky_notok()) def test_fromutc(self): - self.assertRaises(TypeError, Eastern.fromutc) # not enough args + self.assertRaises(TypeError, Eastern.fromutc) # not enough args now = datetime.utcnow().replace(tzinfo=utc_real) - self.assertRaises(ValueError, Eastern.fromutc, now) # wrong tzinfo - now = now.replace(tzinfo=Eastern) # insert correct tzinfo - enow = Eastern.fromutc(now) # doesn't blow up - self.assertEqual(enow.tzinfo, Eastern) # has right tzinfo member - self.assertRaises(TypeError, Eastern.fromutc, now, now) # too many args - self.assertRaises(TypeError, Eastern.fromutc, date.today()) # wrong type + self.assertRaises(ValueError, Eastern.fromutc, now) # wrong tzinfo + now = now.replace(tzinfo=Eastern) # insert correct tzinfo + enow = Eastern.fromutc(now) # doesn't blow up + self.assertEqual(enow.tzinfo, Eastern) # has right tzinfo member + self.assertRaises(TypeError, Eastern.fromutc, now, now) # too many args + self.assertRaises(TypeError, Eastern.fromutc, date.today()) # wrong type # Always converts UTC to standard time. class FauxUSTimeZone(USTimeZone): def fromutc(self, dt): return dt + self.stdoffset - FEastern = FauxUSTimeZone(-5, "FEastern", "FEST", "FEDT") + + FEastern = FauxUSTimeZone(-5, "FEastern", "FEST", "FEDT") # UTC 4:MM 5:MM 6:MM 7:MM 8:MM 9:MM # EST 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM @@ -3740,9 +3831,11 @@ def fromutc(self, dt): ############################################################################# # oddballs -class Oddballs(unittest.TestCase): - @unittest.skip("MicroPython doesn't implement special subclass handling from https://docs.python.org/3/reference/datamodel.html#object.__ror") +class Oddballs(unittest.TestCase): + @unittest.skip( + "MicroPython doesn't implement special subclass handling from https://docs.python.org/3/reference/datamodel.html#object.__ror" + ) def test_bug_1028306(self): # Trying to compare a date to a datetime should act like a mixed- # type comparison, despite that datetime is a subclass of date. @@ -3765,7 +3858,7 @@ def test_bug_1028306(self): # projection if use of a date method is forced. self.assertEqual(as_date.__eq__(as_datetime), True) different_day = (as_date.day + 1) % 20 + 1 - as_different = as_datetime.replace(day= different_day) + as_different = as_datetime.replace(day=different_day) self.assertEqual(as_date.__eq__(as_different), False) # And date should compare with other subclasses of date. If a @@ -3775,13 +3868,14 @@ def test_bug_1028306(self): self.assertEqual(date_sc, as_date) # Ditto for datetimes. - datetime_sc = SubclassDatetime(as_datetime.year, as_datetime.month, - as_date.day, 0, 0, 0) + datetime_sc = SubclassDatetime(as_datetime.year, as_datetime.month, as_date.day, 0, 0, 0) self.assertEqual(as_datetime, datetime_sc) self.assertEqual(datetime_sc, as_datetime) + def test_main(): support.run_unittest(__name__) + if __name__ == "__main__": test_main() diff --git a/fcntl/fcntl.py b/unix-ffi/fcntl/fcntl.py similarity index 100% rename from fcntl/fcntl.py rename to unix-ffi/fcntl/fcntl.py diff --git a/fcntl/metadata.txt b/unix-ffi/fcntl/metadata.txt similarity index 100% rename from fcntl/metadata.txt rename to unix-ffi/fcntl/metadata.txt diff --git a/unix-ffi/fcntl/setup.py b/unix-ffi/fcntl/setup.py new file mode 100644 index 000000000..93fd06136 --- /dev/null +++ b/unix-ffi/fcntl/setup.py @@ -0,0 +1,25 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-fcntl", + version="0.0.4", + description="fcntl module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["fcntl"], + install_requires=["micropython-ffilib"], +) diff --git a/ffilib/ffilib.py b/unix-ffi/ffilib/ffilib.py similarity index 83% rename from ffilib/ffilib.py rename to unix-ffi/ffilib/ffilib.py index dc4d672a2..e79448fea 100644 --- a/ffilib/ffilib.py +++ b/unix-ffi/ffilib/ffilib.py @@ -1,4 +1,5 @@ import sys + try: import ffi except ImportError: @@ -6,6 +7,7 @@ _cache = {} + def open(name, maxver=10, extra=()): if not ffi: return None @@ -13,16 +15,18 @@ def open(name, maxver=10, extra=()): return _cache[name] except KeyError: pass + def libs(): if sys.platform == "linux": - yield '%s.so' % name + yield "%s.so" % name for i in range(maxver, -1, -1): - yield '%s.so.%u' % (name, i) + yield "%s.so.%u" % (name, i) else: - for ext in ('dylib', 'dll'): - yield '%s.%s' % (name, ext) + for ext in ("dylib", "dll"): + yield "%s.%s" % (name, ext) for n in extra: yield n + err = None for n in libs(): try: @@ -33,9 +37,11 @@ def libs(): err = e raise err + def libc(): return open("libc", 6) + # Find out bitness of the platform, even if long ints are not supported # TODO: All bitness differences should be removed from micropython-lib, and # this snippet too. diff --git a/ffilib/metadata.txt b/unix-ffi/ffilib/metadata.txt similarity index 100% rename from ffilib/metadata.txt rename to unix-ffi/ffilib/metadata.txt diff --git a/unix-ffi/ffilib/setup.py b/unix-ffi/ffilib/setup.py new file mode 100644 index 000000000..4cfc15bea --- /dev/null +++ b/unix-ffi/ffilib/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-ffilib", + version="0.1.3", + description="MicroPython FFI helper module", + long_description="MicroPython FFI helper module to easily interface with underlying shared libraries", + url="https://github.com/micropython/micropython-lib", + author="Damien George", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["ffilib"], +) diff --git a/gettext/gettext.py b/unix-ffi/gettext/gettext.py similarity index 100% rename from gettext/gettext.py rename to unix-ffi/gettext/gettext.py diff --git a/gettext/metadata.txt b/unix-ffi/gettext/metadata.txt similarity index 100% rename from gettext/metadata.txt rename to unix-ffi/gettext/metadata.txt diff --git a/unix-ffi/gettext/setup.py b/unix-ffi/gettext/setup.py new file mode 100644 index 000000000..f5cc76fb4 --- /dev/null +++ b/unix-ffi/gettext/setup.py @@ -0,0 +1,25 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-gettext", + version="0.1", + description="gettext module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="Riccardo Magliocchetti", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["gettext"], + install_requires=["micropython-ffilib"], +) diff --git a/unix-ffi/gettext/test_gettext.py b/unix-ffi/gettext/test_gettext.py new file mode 100644 index 000000000..263aa314a --- /dev/null +++ b/unix-ffi/gettext/test_gettext.py @@ -0,0 +1,16 @@ +import gettext + +msg = gettext.gettext("yes") +assert msg == "yes" + +msg = gettext.ngettext("one", "two", 1) +assert msg == "one" + +msg = gettext.ngettext("one", "two", 2) +assert msg == "two" + +msg = gettext.ngettext("one", "two", 0) +assert msg == "two" + +msg = gettext.ngettext("one", "two", "three") +assert msg == "two" diff --git a/machine/example_timer.py b/unix-ffi/machine/example_timer.py similarity index 100% rename from machine/example_timer.py rename to unix-ffi/machine/example_timer.py diff --git a/machine/machine/__init__.py b/unix-ffi/machine/machine/__init__.py similarity index 99% rename from machine/machine/__init__.py rename to unix-ffi/machine/machine/__init__.py index 0b4c690bb..80bf5da1a 100644 --- a/machine/machine/__init__.py +++ b/unix-ffi/machine/machine/__init__.py @@ -2,5 +2,6 @@ from .timer import * from .pin import * + def unique_id(): return b"upy-non-unique" diff --git a/machine/machine/pin.py b/unix-ffi/machine/machine/pin.py similarity index 99% rename from machine/machine/pin.py rename to unix-ffi/machine/machine/pin.py index 746a17e09..9774bf19c 100644 --- a/machine/machine/pin.py +++ b/unix-ffi/machine/machine/pin.py @@ -1,5 +1,6 @@ import umachine + class Pin(umachine.PinBase): IN = "in" diff --git a/machine/machine/timer.py b/unix-ffi/machine/machine/timer.py similarity index 83% rename from machine/machine/timer.py rename to unix-ffi/machine/machine/timer.py index ecd614041..1aa53f936 100644 --- a/machine/machine/timer.py +++ b/unix-ffi/machine/machine/timer.py @@ -41,38 +41,40 @@ timer_create_ = librt.func("i", "timer_create", "ipp") timer_settime_ = librt.func("i", "timer_settime", "PiPp") + def new(sdesc): buf = bytearray(uctypes.sizeof(sdesc)) s = uctypes.struct(uctypes.addressof(buf), sdesc, uctypes.NATIVE) return s + def timer_create(sig_id): sev = new(sigevent_t) - #print(sev) + # print(sev) sev.sigev_notify = SIGEV_SIGNAL sev.sigev_signo = SIGRTMIN + sig_id - timerid = array.array('P', [0]) + timerid = array.array("P", [0]) r = timer_create_(CLOCK_MONOTONIC, sev, timerid) os.check_error(r) - #print("timerid", hex(timerid[0])) + # print("timerid", hex(timerid[0])) return timerid[0] + def timer_settime(tid, hz): period = 1000000000 // hz new_val = new(itimerspec_t) new_val.it_value.tv_nsec = period new_val.it_interval.tv_nsec = period - #print("new_val:", bytes(new_val)) + # print("new_val:", bytes(new_val)) old_val = new(itimerspec_t) - #print(new_val, old_val) + # print(new_val, old_val) r = timer_settime_(tid, 0, new_val, old_val) os.check_error(r) - #print("old_val:", bytes(old_val)) - #print("timer_settime", r) + # print("old_val:", bytes(old_val)) + # print("timer_settime", r) class Timer: - def __init__(self, id, freq): self.id = id self.tid = timer_create(id) @@ -82,8 +84,8 @@ def callback(self, cb): self.cb = cb timer_settime(self.tid, self.freq) org_sig = signal(SIGRTMIN + self.id, self.handler) - #print("Sig %d: %s" % (SIGRTMIN + self.id, org_sig)) + # print("Sig %d: %s" % (SIGRTMIN + self.id, org_sig)) def handler(self, signum): - #print('Signal handler called with signal', signum) + # print('Signal handler called with signal', signum) self.cb(self) diff --git a/machine/metadata.txt b/unix-ffi/machine/metadata.txt similarity index 100% rename from machine/metadata.txt rename to unix-ffi/machine/metadata.txt diff --git a/unix-ffi/machine/setup.py b/unix-ffi/machine/setup.py new file mode 100644 index 000000000..88ecafaf1 --- /dev/null +++ b/unix-ffi/machine/setup.py @@ -0,0 +1,25 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-machine", + version="0.2.1", + description="machine module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + packages=["machine"], + install_requires=["micropython-ffilib", "micropython-os", "micropython-signal"], +) diff --git a/multiprocessing/metadata.txt b/unix-ffi/multiprocessing/metadata.txt similarity index 100% rename from multiprocessing/metadata.txt rename to unix-ffi/multiprocessing/metadata.txt diff --git a/multiprocessing/multiprocessing.py b/unix-ffi/multiprocessing/multiprocessing.py similarity index 99% rename from multiprocessing/multiprocessing.py rename to unix-ffi/multiprocessing/multiprocessing.py index 470b50dbb..79ca4add3 100644 --- a/multiprocessing/multiprocessing.py +++ b/unix-ffi/multiprocessing/multiprocessing.py @@ -4,7 +4,6 @@ class Process: - def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): self.target = target self.args = args @@ -34,7 +33,6 @@ def register_pipe(self, r, w): class Connection: - def __init__(self, fd): self.fd = fd self.f = open(fd) @@ -68,7 +66,6 @@ def Pipe(duplex=True): class AsyncResult: - def __init__(self, p, r): self.p = p self.r = r @@ -90,7 +87,6 @@ def ready(self): class Pool: - def __init__(self, num): self.num = num @@ -99,13 +95,13 @@ def _apply(self, f, args, kwargs): def _exec(w): r = f(*args, **kwargs) w.send(r) + r, w = Pipe(False) p = Process(target=_exec, args=(w,)) p.register_pipe(r, w) p.start() return p, r - def apply(self, f, args=(), kwargs={}): p, r = self._apply(f, args, kwargs) res = r.recv() diff --git a/unix-ffi/multiprocessing/setup.py b/unix-ffi/multiprocessing/setup.py new file mode 100644 index 000000000..62497ea19 --- /dev/null +++ b/unix-ffi/multiprocessing/setup.py @@ -0,0 +1,25 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-multiprocessing", + version="0.1.2", + description="multiprocessing module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["multiprocessing"], + install_requires=["micropython-os", "micropython-select", "micropython-pickle"], +) diff --git a/multiprocessing/test_pipe.py b/unix-ffi/multiprocessing/test_pipe.py similarity index 74% rename from multiprocessing/test_pipe.py rename to unix-ffi/multiprocessing/test_pipe.py index 4e3d56437..b0a223b04 100644 --- a/multiprocessing/test_pipe.py +++ b/unix-ffi/multiprocessing/test_pipe.py @@ -2,14 +2,16 @@ import os from multiprocessing import Process, Pipe + def f(conn): - conn.send([42, None, 'hello']) + conn.send([42, None, "hello"]) conn.send([42, 42, 42]) conn.close() -if __name__ == '__main__': + +if __name__ == "__main__": parent_conn, child_conn = Pipe(False) - #print(parent_conn, child_conn) + # print(parent_conn, child_conn) p = Process(target=f, args=(child_conn,)) # Extension: need to call this for uPy @@ -17,6 +19,6 @@ def f(conn): p.register_pipe(parent_conn, child_conn) p.start() - parent_conn.recv() == [42, None, 'hello'] + parent_conn.recv() == [42, None, "hello"] parent_conn.recv() == [42, 42, 42] p.join() diff --git a/multiprocessing/test_pool.py b/unix-ffi/multiprocessing/test_pool.py similarity index 83% rename from multiprocessing/test_pool.py rename to unix-ffi/multiprocessing/test_pool.py index cb98e6ef2..e16013e2d 100644 --- a/multiprocessing/test_pool.py +++ b/unix-ffi/multiprocessing/test_pool.py @@ -1,7 +1,9 @@ from multiprocessing import Pool + def f(x): - return x*x + return x * x + pool = Pool(4) assert pool.apply(f, (10,)) == 100 diff --git a/multiprocessing/test_pool_async.py b/unix-ffi/multiprocessing/test_pool_async.py similarity index 88% rename from multiprocessing/test_pool_async.py rename to unix-ffi/multiprocessing/test_pool_async.py index 1c4816892..f9c472225 100644 --- a/multiprocessing/test_pool_async.py +++ b/unix-ffi/multiprocessing/test_pool_async.py @@ -1,21 +1,25 @@ import time from multiprocessing import Pool + def f(x): - return x*x + return x * x + pool = Pool(4) future = pool.apply_async(f, (10,)) assert future.get() == 100 + def f2(x): time.sleep(0.5) return x + 1 + future = pool.apply_async(f2, (10,)) iter = 0 while not future.ready(): - #print("not ready") + # print("not ready") time.sleep(0.1) iter += 1 @@ -31,14 +35,14 @@ def f2(x): iter = 0 while True: - #not all(futs): + # not all(futs): c = 0 for f in futs: if not f.ready(): c += 1 if not c: break - #print("not ready2") + # print("not ready2") time.sleep(0.1) iter += 1 diff --git a/unix-ffi/multiprocessing/test_process.py b/unix-ffi/multiprocessing/test_process.py new file mode 100644 index 000000000..80ed5e71d --- /dev/null +++ b/unix-ffi/multiprocessing/test_process.py @@ -0,0 +1,11 @@ +from multiprocessing import Process + + +def f(name): + assert name == "bob" + + +if __name__ == "__main__": + p = Process(target=f, args=("bob",)) + p.start() + p.join() diff --git a/os/example_dirs.py b/unix-ffi/os/example_dirs.py similarity index 100% rename from os/example_dirs.py rename to unix-ffi/os/example_dirs.py diff --git a/os/example_fork.py b/unix-ffi/os/example_fork.py similarity index 100% rename from os/example_fork.py rename to unix-ffi/os/example_fork.py diff --git a/os/example_fsencode.py b/unix-ffi/os/example_fsencode.py similarity index 100% rename from os/example_fsencode.py rename to unix-ffi/os/example_fsencode.py diff --git a/os/example_getenv.py b/unix-ffi/os/example_getenv.py similarity index 100% rename from os/example_getenv.py rename to unix-ffi/os/example_getenv.py diff --git a/os/example_open.py b/unix-ffi/os/example_open.py similarity index 100% rename from os/example_open.py rename to unix-ffi/os/example_open.py diff --git a/os/example_rw.py b/unix-ffi/os/example_rw.py similarity index 100% rename from os/example_rw.py rename to unix-ffi/os/example_rw.py diff --git a/os/example_system.py b/unix-ffi/os/example_system.py similarity index 100% rename from os/example_system.py rename to unix-ffi/os/example_system.py diff --git a/os/example_urandom.py b/unix-ffi/os/example_urandom.py similarity index 100% rename from os/example_urandom.py rename to unix-ffi/os/example_urandom.py diff --git a/os/metadata.txt b/unix-ffi/os/metadata.txt similarity index 100% rename from os/metadata.txt rename to unix-ffi/os/metadata.txt diff --git a/os/os/__init__.py b/unix-ffi/os/os/__init__.py similarity index 94% rename from os/os/__init__.py rename to unix-ffi/os/os/__init__.py index f941e7f54..3cca078f9 100644 --- a/os/os/__init__.py +++ b/unix-ffi/os/os/__init__.py @@ -10,15 +10,15 @@ X_OK = const(1) F_OK = const(0) -O_ACCMODE = 0o0000003 -O_RDONLY = 0o0000000 -O_WRONLY = 0o0000001 -O_RDWR = 0o0000002 -O_CREAT = 0o0000100 -O_EXCL = 0o0000200 -O_NOCTTY = 0o0000400 -O_TRUNC = 0o0001000 -O_APPEND = 0o0002000 +O_ACCMODE = 0o0000003 +O_RDONLY = 0o0000000 +O_WRONLY = 0o0000001 +O_RDWR = 0o0000002 +O_CREAT = 0o0000100 +O_EXCL = 0o0000200 +O_NOCTTY = 0o0000400 +O_TRUNC = 0o0001000 +O_APPEND = 0o0002000 O_NONBLOCK = 0o0004000 error = OSError @@ -57,7 +57,6 @@ getenv_ = libc.func("s", "getenv", "P") - def check_error(ret): # Return True is error was EINTR (which usually means that OS call # should be restarted). @@ -67,32 +66,42 @@ def check_error(ret): return True raise OSError(e) + def raise_error(): raise OSError(uos.errno()) + stat = uos.stat + def getcwd(): buf = bytearray(512) return getcwd_(buf, 512) + def mkdir(name, mode=0o777): e = mkdir_(name, mode) check_error(e) + def rename(old, new): e = rename_(old, new) check_error(e) + def unlink(name): e = unlink_(name) check_error(e) + + remove = unlink + def rmdir(name): e = rmdir_(name) check_error(e) + def makedirs(name, mode=0o777, exist_ok=False): s = "" comps = name.split("/") @@ -110,9 +119,11 @@ def makedirs(name, mode=0o777, exist_ok=False): return raise e + if hasattr(uos, "ilistdir"): ilistdir = uos.ilistdir else: + def ilistdir(path="."): dir = opendir_(path) if not dir: @@ -124,11 +135,13 @@ def ilistdir(path="."): if not dirent: break import uctypes + dirent = uctypes.bytes_at(dirent, struct.calcsize(dirent_fmt)) dirent = struct.unpack(dirent_fmt, dirent) - dirent = (dirent[-1].split(b'\0', 1)[0], dirent[-2], dirent[0]) + dirent = (dirent[-1].split(b"\0", 1)[0], dirent[-2], dirent[0]) yield dirent + def listdir(path="."): is_bytes = isinstance(path, bytes) res = [] @@ -144,6 +157,7 @@ def listdir(path="."): res.append(fname) return res + def walk(top, topdown=True): files = [] dirs = [] @@ -162,55 +176,67 @@ def walk(top, topdown=True): if not topdown: yield top, dirs, files + def open(n, flags, mode=0o777): r = open_(n, flags, mode) check_error(r) return r + def read(fd, n): buf = bytearray(n) r = read_(fd, buf, n) check_error(r) return bytes(buf[:r]) + def write(fd, buf): r = write_(fd, buf, len(buf)) check_error(r) return r + def close(fd): r = close_(fd) check_error(r) return r + def dup(fd): r = dup_(fd) check_error(r) return r + def access(path, mode): return access_(path, mode) == 0 + def chdir(dir): r = chdir_(dir) check_error(r) + def fork(): r = fork_() check_error(r) return r + def pipe(): - a = array.array('i', [0, 0]) + a = array.array("i", [0, 0]) r = pipe_(a) check_error(r) return a[0], a[1] + def _exit(n): _exit_(n) + def execvp(f, args): import uctypes + args_ = array.array("P", [0] * (len(args) + 1)) i = 0 for a in args: @@ -219,35 +245,42 @@ def execvp(f, args): r = execvp_(f, uctypes.addressof(args_)) check_error(r) + def getpid(): return getpid_() + def waitpid(pid, opts): - a = array.array('i', [0]) + a = array.array("i", [0]) r = waitpid_(pid, a, opts) check_error(r) return (r, a[0]) + def kill(pid, sig): r = kill_(pid, sig) check_error(r) + def system(command): r = system_(command) check_error(r) return r + def getenv(var, default=None): var = getenv_(var) if var is None: return default return var + def fsencode(s): if type(s) is bytes: return s return bytes(s, "utf-8") + def fsdecode(s): if type(s) is str: return s @@ -256,11 +289,14 @@ def fsdecode(s): def urandom(n): import builtins + with builtins.open("/dev/urandom", "rb") as f: return f.read(n) + def popen(cmd, mode="r"): import builtins + i, o = pipe() if mode[0] == "w": i, o = o, i diff --git a/unix-ffi/os/setup.py b/unix-ffi/os/setup.py new file mode 100644 index 000000000..9d4219dad --- /dev/null +++ b/unix-ffi/os/setup.py @@ -0,0 +1,25 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-os", + version="0.6", + description="os module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + packages=["os"], + install_requires=["micropython-ffilib", "micropython-errno", "micropython-stat"], +) diff --git a/os/test_filestat.py b/unix-ffi/os/test_filestat.py similarity index 100% rename from os/test_filestat.py rename to unix-ffi/os/test_filestat.py diff --git a/pwd/metadata.txt b/unix-ffi/pwd/metadata.txt similarity index 100% rename from pwd/metadata.txt rename to unix-ffi/pwd/metadata.txt diff --git a/pwd/pwd.py b/unix-ffi/pwd/pwd.py similarity index 78% rename from pwd/pwd.py rename to unix-ffi/pwd/pwd.py index c973b9b2a..29ebe3416 100644 --- a/pwd/pwd.py +++ b/unix-ffi/pwd/pwd.py @@ -10,8 +10,9 @@ getpwnam_ = libc.func("P", "getpwnam", "s") -struct_passwd = namedtuple("struct_passwd", - ["pw_name", "pw_passwd", "pw_uid", "pw_gid", "pw_gecos", "pw_dir", "pw_shell"]) +struct_passwd = namedtuple( + "struct_passwd", ["pw_name", "pw_passwd", "pw_uid", "pw_gid", "pw_gecos", "pw_dir", "pw_shell"] +) def getpwnam(user): diff --git a/unix-ffi/pwd/setup.py b/unix-ffi/pwd/setup.py new file mode 100644 index 000000000..811836932 --- /dev/null +++ b/unix-ffi/pwd/setup.py @@ -0,0 +1,25 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-pwd", + version="0.1", + description="pwd module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="Riccardo Magliocchetti", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["pwd"], + install_requires=["micropython-ffilib"], +) diff --git a/pwd/test_getpwnam.py b/unix-ffi/pwd/test_getpwnam.py similarity index 81% rename from pwd/test_getpwnam.py rename to unix-ffi/pwd/test_getpwnam.py index ac836d52f..ffb322286 100644 --- a/pwd/test_getpwnam.py +++ b/unix-ffi/pwd/test_getpwnam.py @@ -1,7 +1,7 @@ import pwd import os -user = os.getenv('USER') +user = os.getenv("USER") passwd = pwd.getpwnam(user) assert passwd assert isinstance(passwd, pwd.struct_passwd) diff --git a/pyb/example_blink.py b/unix-ffi/pyb/example_blink.py similarity index 91% rename from pyb/example_blink.py rename to unix-ffi/pyb/example_blink.py index f49703921..9483bfe0d 100644 --- a/pyb/example_blink.py +++ b/unix-ffi/pyb/example_blink.py @@ -4,7 +4,7 @@ l = LED("left:amber") print(l.get()) while 1: -# l.on() + # l.on() l.toggle() print(l.get()) time.sleep(1) diff --git a/pyb/pyb.py b/unix-ffi/pyb/pyb.py similarity index 99% rename from pyb/pyb.py rename to unix-ffi/pyb/pyb.py index 14e3cf5b6..f1b6f6542 100644 --- a/pyb/pyb.py +++ b/unix-ffi/pyb/pyb.py @@ -1,5 +1,4 @@ class LED: - def __init__(self, id): self.f = open("/sys/class/leds/%s/brightness" % id, "r+b") diff --git a/re-pcre/metadata.txt b/unix-ffi/re-pcre/metadata.txt similarity index 100% rename from re-pcre/metadata.txt rename to unix-ffi/re-pcre/metadata.txt diff --git a/re-pcre/re.py b/unix-ffi/re-pcre/re.py similarity index 89% rename from re-pcre/re.py rename to unix-ffi/re-pcre/re.py index 1d0a39274..d37584320 100644 --- a/re-pcre/re.py +++ b/unix-ffi/re-pcre/re.py @@ -34,7 +34,6 @@ class PCREMatch: - def __init__(self, s, num_matches, offsets): self.s = s self.num = num_matches @@ -42,36 +41,35 @@ def __init__(self, s, num_matches, offsets): def group(self, *n): if not n: - return self.s[self.offsets[0]:self.offsets[1]] + return self.s[self.offsets[0] : self.offsets[1]] if len(n) == 1: - return self.s[self.offsets[n[0]*2]:self.offsets[n[0]*2+1]] - return tuple(self.s[self.offsets[i*2]:self.offsets[i*2+1]] for i in n) + return self.s[self.offsets[n[0] * 2] : self.offsets[n[0] * 2 + 1]] + return tuple(self.s[self.offsets[i * 2] : self.offsets[i * 2 + 1]] for i in n) def groups(self, default=None): assert default is None return tuple(self.group(i + 1) for i in range(self.num - 1)) def start(self, n=0): - return self.offsets[n*2] + return self.offsets[n * 2] def end(self, n=0): - return self.offsets[n*2+1] + return self.offsets[n * 2 + 1] def span(self, n=0): - return self.offsets[n*2], self.offsets[n*2+1] + return self.offsets[n * 2], self.offsets[n * 2 + 1] class PCREPattern: - def __init__(self, compiled_ptn): self.obj = compiled_ptn def search(self, s, pos=0, endpos=-1, _flags=0): assert endpos == -1, "pos: %d, endpos: %d" % (pos, endpos) - buf = array.array('i', [0]) + buf = array.array("i", [0]) pcre_fullinfo(self.obj, None, PCRE_INFO_CAPTURECOUNT, buf) cap_count = buf[0] - ov = array.array('i', [0, 0, 0] * (cap_count + 1)) + ov = array.array("i", [0, 0, 0] * (cap_count + 1)) num = pcre_exec(self.obj, None, s, len(s), pos, _flags, ov, len(ov)) if num == -1: # No match @@ -169,6 +167,7 @@ def split(pattern, s, maxsplit=0, flags=0): r = compile(pattern, flags) return r.split(s, maxsplit) + def findall(pattern, s, flags=0): r = compile(pattern, flags) return r.findall(s) @@ -177,7 +176,7 @@ def findall(pattern, s, flags=0): def escape(s): res = "" for c in s: - if '0' <= c <= '9' or 'A' <= c <= 'Z' or 'a' <= c <= 'z' or c == '_': + if "0" <= c <= "9" or "A" <= c <= "Z" or "a" <= c <= "z" or c == "_": res += c else: res += "\\" + c diff --git a/unix-ffi/re-pcre/setup.py b/unix-ffi/re-pcre/setup.py new file mode 100644 index 000000000..f624e6250 --- /dev/null +++ b/unix-ffi/re-pcre/setup.py @@ -0,0 +1,25 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-re-pcre", + version="0.2.5", + description="re-pcre module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["re"], + install_requires=["micropython-ffilib"], +) diff --git a/re-pcre/test_re.py b/unix-ffi/re-pcre/test_re.py similarity index 57% rename from re-pcre/test_re.py rename to unix-ffi/re-pcre/test_re.py index 8e8f3afc6..e58e8b8b8 100644 --- a/re-pcre/test_re.py +++ b/unix-ffi/re-pcre/test_re.py @@ -20,35 +20,43 @@ assert re.sub("a", lambda m: m.group(0) * 2, "caaab") == "caaaaaab" m = re.match(r"(\d+)\.(\d+)", "24.1632") -assert m.groups() == ('24', '1632') -assert m.group(2, 1) == ('1632', '24') +assert m.groups() == ("24", "1632") +assert m.group(2, 1) == ("1632", "24") assert re.escape(r"1243*&[]_dsfAd") == r"1243\*\&\[\]_dsfAd" -assert re.split('x*', 'foo') == ['foo'] +assert re.split("x*", "foo") == ["foo"] assert re.split("(?m)^$", "foo\n\nbar\n") == ["foo\n\nbar\n"] -assert re.split('\W+', 'Words, words, words.') == ['Words', 'words', 'words', ''] -assert re.split('(\W+)', 'Words, words, words.') == ['Words', ', ', 'words', ', ', 'words', '.', ''] -assert re.split('\W+', 'Words, words, words.', 1) == ['Words', 'words, words.'] -assert re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE) == ['0', '3', '9'] -assert re.split('(\W+)', '...words, words...') == ['', '...', 'words', ', ', 'words', '...', ''] +assert re.split("\W+", "Words, words, words.") == ["Words", "words", "words", ""] +assert re.split("(\W+)", "Words, words, words.") == [ + "Words", + ", ", + "words", + ", ", + "words", + ".", + "", +] +assert re.split("\W+", "Words, words, words.", 1) == ["Words", "words, words."] +assert re.split("[a-f]+", "0a3B9", flags=re.IGNORECASE) == ["0", "3", "9"] +assert re.split("(\W+)", "...words, words...") == ["", "...", "words", ", ", "words", "...", ""] assert re.sub(r"[ :/?&]", "_", "http://foo.ua/bar/?a=1&b=baz/") == "http___foo.ua_bar__a=1_b=baz_" text = "He was carefully disguised but captured quickly by police." -assert re.findall(r"\w+ly", text) == ['carefully', 'quickly'] +assert re.findall(r"\w+ly", text) == ["carefully", "quickly"] text = "He was carefully disguised but captured quickly by police." -assert re.findall(r"(\w+)(ly)", text) == [('careful', 'ly'), ('quick', 'ly')] +assert re.findall(r"(\w+)(ly)", text) == [("careful", "ly"), ("quick", "ly")] text = "He was carefully disguised but captured quickly by police." -assert re.findall(r"(\w+)ly", text) == ['careful', 'quick'] +assert re.findall(r"(\w+)ly", text) == ["careful", "quick"] -_leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE) +_leading_whitespace_re = re.compile("(^[ \t]*)(?:[^ \t\n])", re.MULTILINE) text = "\tfoo\n\tbar" indents = _leading_whitespace_re.findall(text) -assert indents == ['\t', '\t'] +assert indents == ["\t", "\t"] text = " \thello there\n \t how are you?" indents = _leading_whitespace_re.findall(text) -assert indents == [' \t', ' \t '] +assert indents == [" \t", " \t "] diff --git a/select/example_epoll.py b/unix-ffi/select/example_epoll.py similarity index 70% rename from select/example_epoll.py rename to unix-ffi/select/example_epoll.py index 346fc2af9..38c32cc7b 100644 --- a/select/example_epoll.py +++ b/unix-ffi/select/example_epoll.py @@ -3,7 +3,7 @@ ep = select.epoll() -ep.register(0, select.EPOLLIN, (lambda x:x, (0,))) +ep.register(0, select.EPOLLIN, (lambda x: x, (0,))) res = ep.poll(2000) print(res) for ev, fd in res: diff --git a/select/metadata.txt b/unix-ffi/select/metadata.txt similarity index 100% rename from select/metadata.txt rename to unix-ffi/select/metadata.txt diff --git a/select/select.py b/unix-ffi/select/select.py similarity index 90% rename from select/select.py rename to unix-ffi/select/select.py index 0ba96e166..eec9bfb81 100644 --- a/select/select.py +++ b/unix-ffi/select/select.py @@ -10,11 +10,11 @@ libc = ffilib.libc() -#int epoll_create(int size); +# int epoll_create(int size); epoll_create = libc.func("i", "epoll_create", "i") -#int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event); +# int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event); epoll_ctl = libc.func("i", "epoll_ctl", "iiiP") -#int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout); +# int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout); epoll_wait = libc.func("i", "epoll_wait", "ipii") EPOLLIN = 0x001 @@ -24,7 +24,7 @@ EPOLLHUP = 0x010 EPOLLRDHUP = 0x2000 EPOLLONESHOT = 1 << 30 -EPOLLET = 1 << 31 +EPOLLET = 1 << 31 EPOLL_CTL_ADD = 1 EPOLL_CTL_DEL = 2 @@ -46,14 +46,14 @@ else: epoll_event = "QO" -class Epoll: +class Epoll: def __init__(self, epfd): self.epfd = epfd self.evbuf = struct.pack(epoll_event, 0, None) self.registry = {} - def register(self, fd, eventmask=EPOLLIN|EPOLLPRI|EPOLLOUT, retval=None): + def register(self, fd, eventmask=EPOLLIN | EPOLLPRI | EPOLLOUT, retval=None): "retval is extension to stdlib, value to use in results from .poll()." if retval is None: retval = fd diff --git a/unix-ffi/select/setup.py b/unix-ffi/select/setup.py new file mode 100644 index 000000000..887b5b9d9 --- /dev/null +++ b/unix-ffi/select/setup.py @@ -0,0 +1,25 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-select", + version="0.3", + description="select module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["select"], + install_requires=["micropython-os", "micropython-ffilib"], +) diff --git a/signal/example_sigint.py b/unix-ffi/signal/example_sigint.py similarity index 82% rename from signal/example_sigint.py rename to unix-ffi/signal/example_sigint.py index 860d82d7e..cf9adcbde 100644 --- a/signal/example_sigint.py +++ b/unix-ffi/signal/example_sigint.py @@ -3,10 +3,12 @@ quit = 0 + def handler(signum): global quit quit = 1 - print('Signal handler called with signal', signum) + print("Signal handler called with signal", signum) + print("org signal() val:", signal(SIGINT, handler)) print("read back signal() val:", signal(SIGINT, handler)) diff --git a/signal/example_sigint_exc.py b/unix-ffi/signal/example_sigint_exc.py similarity index 81% rename from signal/example_sigint_exc.py rename to unix-ffi/signal/example_sigint_exc.py index 4e0a721ba..b308d534c 100644 --- a/signal/example_sigint_exc.py +++ b/unix-ffi/signal/example_sigint_exc.py @@ -3,12 +3,14 @@ quit = 0 + def handler(signum): global quit -# quit = 1 - print('Signal handler called with signal', signum) + # quit = 1 + print("Signal handler called with signal", signum) raise OSError("Couldn't open device!") + print("org signal() val:", signal(SIGINT, handler)) print("read back signal() val:", signal(SIGINT, handler)) diff --git a/signal/example_sigint_ign.py b/unix-ffi/signal/example_sigint_ign.py similarity index 100% rename from signal/example_sigint_ign.py rename to unix-ffi/signal/example_sigint_ign.py diff --git a/signal/metadata.txt b/unix-ffi/signal/metadata.txt similarity index 100% rename from signal/metadata.txt rename to unix-ffi/signal/metadata.txt diff --git a/unix-ffi/signal/setup.py b/unix-ffi/signal/setup.py new file mode 100644 index 000000000..d13328343 --- /dev/null +++ b/unix-ffi/signal/setup.py @@ -0,0 +1,25 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-signal", + version="0.3.2", + description="signal module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["signal"], + install_requires=["micropython-ffilib"], +) diff --git a/signal/signal.py b/unix-ffi/signal/signal.py similarity index 99% rename from signal/signal.py rename to unix-ffi/signal/signal.py index c41eb2bdd..fd60b9ee2 100644 --- a/signal/signal.py +++ b/unix-ffi/signal/signal.py @@ -13,9 +13,11 @@ signal_i = libc.func("i", "signal", "ii") signal_p = libc.func("i", "signal", "ip") + def signal(n, handler): if isinstance(handler, int): return signal_i(n, handler) import ffi + cb = ffi.callback("v", handler, "i") return signal_p(n, cb) diff --git a/sqlite3/metadata.txt b/unix-ffi/sqlite3/metadata.txt similarity index 100% rename from sqlite3/metadata.txt rename to unix-ffi/sqlite3/metadata.txt diff --git a/unix-ffi/sqlite3/setup.py b/unix-ffi/sqlite3/setup.py new file mode 100644 index 000000000..79226dd2b --- /dev/null +++ b/unix-ffi/sqlite3/setup.py @@ -0,0 +1,25 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-sqlite3", + version="0.2.4", + description="sqlite3 module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["sqlite3"], + install_requires=["micropython-ffilib"], +) diff --git a/sqlite3/sqlite3.py b/unix-ffi/sqlite3/sqlite3.py similarity index 81% rename from sqlite3/sqlite3.py rename to unix-ffi/sqlite3/sqlite3.py index de18a03e5..0f00ff508 100644 --- a/sqlite3/sqlite3.py +++ b/unix-ffi/sqlite3/sqlite3.py @@ -5,51 +5,51 @@ sq3 = ffilib.open("libsqlite3") sqlite3_open = sq3.func("i", "sqlite3_open", "sp") -#int sqlite3_close(sqlite3*); +# int sqlite3_close(sqlite3*); sqlite3_close = sq3.func("i", "sqlite3_close", "p") -#int sqlite3_prepare( +# int sqlite3_prepare( # sqlite3 *db, /* Database handle */ # const char *zSql, /* SQL statement, UTF-8 encoded */ # int nByte, /* Maximum length of zSql in bytes. */ # sqlite3_stmt **ppStmt, /* OUT: Statement handle */ # const char **pzTail /* OUT: Pointer to unused portion of zSql */ -#); +# ); sqlite3_prepare = sq3.func("i", "sqlite3_prepare", "psipp") -#int sqlite3_finalize(sqlite3_stmt *pStmt); +# int sqlite3_finalize(sqlite3_stmt *pStmt); sqlite3_finalize = sq3.func("i", "sqlite3_finalize", "p") -#int sqlite3_step(sqlite3_stmt*); +# int sqlite3_step(sqlite3_stmt*); sqlite3_step = sq3.func("i", "sqlite3_step", "p") -#int sqlite3_column_count(sqlite3_stmt *pStmt); +# int sqlite3_column_count(sqlite3_stmt *pStmt); sqlite3_column_count = sq3.func("i", "sqlite3_column_count", "p") -#int sqlite3_column_type(sqlite3_stmt*, int iCol); +# int sqlite3_column_type(sqlite3_stmt*, int iCol); sqlite3_column_type = sq3.func("i", "sqlite3_column_type", "pi") sqlite3_column_int = sq3.func("i", "sqlite3_column_int", "pi") # using "d" return type gives wrong results sqlite3_column_double = sq3.func("d", "sqlite3_column_double", "pi") sqlite3_column_text = sq3.func("s", "sqlite3_column_text", "pi") -#sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); +# sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); # TODO: should return long int sqlite3_last_insert_rowid = sq3.func("i", "sqlite3_last_insert_rowid", "p") -#const char *sqlite3_errmsg(sqlite3*); +# const char *sqlite3_errmsg(sqlite3*); sqlite3_errmsg = sq3.func("s", "sqlite3_errmsg", "p") # Too recent ##const char *sqlite3_errstr(int); -#sqlite3_errstr = sq3.func("s", "sqlite3_errstr", "i") +# sqlite3_errstr = sq3.func("s", "sqlite3_errstr", "i") -SQLITE_OK = 0 -SQLITE_ERROR = 1 -SQLITE_BUSY = 5 -SQLITE_MISUSE = 21 -SQLITE_ROW = 100 -SQLITE_DONE = 101 +SQLITE_OK = 0 +SQLITE_ERROR = 1 +SQLITE_BUSY = 5 +SQLITE_MISUSE = 21 +SQLITE_ROW = 100 +SQLITE_DONE = 101 -SQLITE_INTEGER = 1 -SQLITE_FLOAT = 2 -SQLITE_TEXT = 3 -SQLITE_BLOB = 4 -SQLITE_NULL = 5 +SQLITE_INTEGER = 1 +SQLITE_FLOAT = 2 +SQLITE_TEXT = 3 +SQLITE_BLOB = 4 +SQLITE_NULL = 5 class Error(Exception): @@ -62,7 +62,6 @@ def check_error(db, s): class Connections: - def __init__(self, h): self.h = h @@ -75,7 +74,6 @@ def close(self): class Cursor: - def __init__(self, h): self.h = h self.stmnt = None @@ -89,9 +87,9 @@ def execute(self, sql, params=None): s = sqlite3_prepare(self.h, sql, -1, b, None) check_error(self.h, s) self.stmnt = int.from_bytes(b, sys.byteorder) - #print("stmnt", self.stmnt) + # print("stmnt", self.stmnt) self.num_cols = sqlite3_column_count(self.stmnt) - #print("num_cols", self.num_cols) + # print("num_cols", self.num_cols) # If it's not select, actually execute it here # num_cols == 0 for statements which don't return data (=> modify it) if not self.num_cols: @@ -107,7 +105,7 @@ def make_row(self): res = [] for i in range(self.num_cols): t = sqlite3_column_type(self.stmnt, i) - #print("type", t) + # print("type", t) if t == SQLITE_INTEGER: res.append(sqlite3_column_int(self.stmnt, i)) elif t == SQLITE_FLOAT: @@ -120,7 +118,7 @@ def make_row(self): def fetchone(self): res = sqlite3_step(self.stmnt) - #print("step:", res) + # print("step:", res) if res == SQLITE_DONE: return None if res == SQLITE_ROW: diff --git a/sqlite3/test_sqlite3.py b/unix-ffi/sqlite3/test_sqlite3.py similarity index 87% rename from sqlite3/test_sqlite3.py rename to unix-ffi/sqlite3/test_sqlite3.py index 0c040f590..39dc07549 100644 --- a/sqlite3/test_sqlite3.py +++ b/unix-ffi/sqlite3/test_sqlite3.py @@ -6,7 +6,7 @@ cur = conn.cursor() cur.execute("SELECT 1, 'foo', 3.0 UNION SELECT 3, 3, 3") -expected = [(1, 'foo', 3.0), (3, 3, 3)] +expected = [(1, "foo", 3.0), (3, 3, 3)] while True: row = cur.fetchone() diff --git a/sqlite3/test_sqlite3_2.py b/unix-ffi/sqlite3/test_sqlite3_2.py similarity index 100% rename from sqlite3/test_sqlite3_2.py rename to unix-ffi/sqlite3/test_sqlite3_2.py diff --git a/time/example_strftime.py b/unix-ffi/time/example_strftime.py similarity index 100% rename from time/example_strftime.py rename to unix-ffi/time/example_strftime.py diff --git a/time/example_time_tuple.py b/unix-ffi/time/example_time_tuple.py similarity index 100% rename from time/example_time_tuple.py rename to unix-ffi/time/example_time_tuple.py diff --git a/time/metadata.txt b/unix-ffi/time/metadata.txt similarity index 100% rename from time/metadata.txt rename to unix-ffi/time/metadata.txt diff --git a/unix-ffi/time/setup.py b/unix-ffi/time/setup.py new file mode 100644 index 000000000..c3ad0332a --- /dev/null +++ b/unix-ffi/time/setup.py @@ -0,0 +1,25 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-time", + version="0.5", + description="time module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="micropython-lib Developers", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["time"], + install_requires=["micropython-ffilib"], +) diff --git a/unix-ffi/time/test_strftime.py b/unix-ffi/time/test_strftime.py new file mode 100644 index 000000000..fc2daebb6 --- /dev/null +++ b/unix-ffi/time/test_strftime.py @@ -0,0 +1,36 @@ +from time import strftime + +# These tuples were generated using localtime() and gmtime() in CPython. +INPUT = ( + (2017, 1, 1, 23, 40, 39, 6, 222, 1), + (2010, 2, 28, 9, 59, 60, 1, 111, 0), + (2000, 3, 31, 1, 33, 0, 2, 44, 1), + (2020, 4, 30, 21, 22, 59, 3, 234, 0), + (1977, 5, 15, 23, 55, 1, 4, 123, 1), + (1940, 6, 11, 9, 21, 33, 5, 55, 0), + (1918, 7, 24, 6, 12, 44, 7, 71, 1), + (1800, 8, 17, 0, 59, 55, 3, 89, 0), + (2222, 9, 5, 1, 0, 4, 2, 255, 1), + (2017, 10, 10, 9, 1, 5, 6, 200, 0), + (2016, 11, 7, 18, 8, 16, 7, 100, 1), + (2001, 12, 2, 12, 19, 27, 1, 33, 0), +) + +# These values were generated using strftime() in CPython. +EXPECTED = ( + ("20170101234039"), + ("20100228095960"), + ("20000331013300"), + ("20200430212259"), + ("19770515235501"), + ("19400611092133"), + ("19180724061244"), + ("18000817005955"), + ("22220905010004"), + ("20171010090105"), + ("20161107180816"), + ("20011202121927"), +) + +for i in range(len(INPUT)): + assert strftime("%Y%m%d%H%M%S", INPUT[i]) == EXPECTED[i] diff --git a/time/time.py b/unix-ffi/time/time.py similarity index 71% rename from time/time.py rename to unix-ffi/time/time.py index f46a0764f..075d904f5 100644 --- a/time/time.py +++ b/unix-ffi/time/time.py @@ -17,16 +17,34 @@ strftime_ = libc.func("i", "strftime", "sisP") mktime_ = libc.func("i", "mktime", "P") -_struct_time = namedtuple("struct_time", - ["tm_year", "tm_mon", "tm_mday", "tm_hour", "tm_min", "tm_sec", "tm_wday", "tm_yday", "tm_isdst"]) +_struct_time = namedtuple( + "struct_time", + [ + "tm_year", + "tm_mon", + "tm_mday", + "tm_hour", + "tm_min", + "tm_sec", + "tm_wday", + "tm_yday", + "tm_isdst", + ], +) + def _tuple_to_c_tm(t): - return ustruct.pack("@iiiiiiiii", t[5], t[4], t[3], t[2], t[1] - 1, t[0] - 1900, (t[6] + 1) % 7, t[7] - 1, t[8]) + return ustruct.pack( + "@iiiiiiiii", t[5], t[4], t[3], t[2], t[1] - 1, t[0] - 1900, (t[6] + 1) % 7, t[7] - 1, t[8] + ) def _c_tm_to_tuple(tm): t = ustruct.unpack("@iiiiiiiii", tm) - return _struct_time(t[5] + 1900, t[4] + 1, t[3], t[2], t[1], t[0], (t[6] - 1) % 7, t[7] + 1, t[8]) + return _struct_time( + t[5] + 1900, t[4] + 1, t[3], t[2], t[1], t[0], (t[6] - 1) % 7, t[7] + 1, t[8] + ) + def struct_time(tm): return _struct_time(*tm) @@ -46,7 +64,7 @@ def localtime(t=None): t = time() t = int(t) - a = ustruct.pack('l', t) + a = ustruct.pack("l", t) tm_p = localtime_(a) return _c_tm_to_tuple(uctypes.bytearray_at(tm_p, 36)) @@ -56,7 +74,7 @@ def gmtime(t=None): t = time() t = int(t) - a = ustruct.pack('l', t) + a = ustruct.pack("l", t) tm_p = gmtime_(a) return _c_tm_to_tuple(uctypes.bytearray_at(tm_p, 36)) @@ -68,6 +86,7 @@ def mktime(tt): def perf_counter(): return time() + def process_time(): return clock() diff --git a/tty/metadata.txt b/unix-ffi/tty/metadata.txt similarity index 100% rename from tty/metadata.txt rename to unix-ffi/tty/metadata.txt diff --git a/unix-ffi/tty/setup.py b/unix-ffi/tty/setup.py new file mode 100644 index 000000000..199c37e97 --- /dev/null +++ b/unix-ffi/tty/setup.py @@ -0,0 +1,24 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-tty", + version="1.0.1", + description="tty module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="micropython-lib Developers", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + py_modules=["tty"], +) diff --git a/tty/tty.py b/unix-ffi/tty/tty.py similarity index 100% rename from tty/tty.py rename to unix-ffi/tty/tty.py diff --git a/ucurses/metadata.txt b/unix-ffi/ucurses/metadata.txt similarity index 100% rename from ucurses/metadata.txt rename to unix-ffi/ucurses/metadata.txt diff --git a/unix-ffi/ucurses/setup.py b/unix-ffi/ucurses/setup.py new file mode 100644 index 000000000..04dbde756 --- /dev/null +++ b/unix-ffi/ucurses/setup.py @@ -0,0 +1,25 @@ +import sys + +# Remove current dir from sys.path, otherwise setuptools will peek up our +# module instead of system's. +sys.path.pop(0) +from setuptools import setup + +sys.path.append("..") +import sdist_upip + +setup( + name="micropython-ucurses", + version="0.1.2", + description="ucurses module for MicroPython", + long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", + url="https://github.com/micropython/micropython-lib", + author="Paul Sokolovsky", + author_email="micro-python@googlegroups.com", + maintainer="micropython-lib Developers", + maintainer_email="micro-python@googlegroups.com", + license="MIT", + cmdclass={"sdist": sdist_upip.sdist}, + packages=["ucurses"], + install_requires=["micropython-os", "micropython-tty", "micropython-select"], +) diff --git a/ucurses/ucurses/__init__.py b/unix-ffi/ucurses/ucurses/__init__.py similarity index 84% rename from ucurses/ucurses/__init__.py rename to unix-ffi/ucurses/ucurses/__init__.py index 98cb9230b..688df745c 100644 --- a/ucurses/ucurses/__init__.py +++ b/unix-ffi/ucurses/ucurses/__init__.py @@ -2,14 +2,14 @@ import tty, termios import select -COLOR_BLACK = 0 -COLOR_RED = 1 -COLOR_GREEN = 2 -COLOR_YELLOW = 3 -COLOR_BLUE = 4 -COLOR_MAGENTA = 5 -COLOR_CYAN = 6 -COLOR_WHITE = 7 +COLOR_BLACK = 0 +COLOR_RED = 1 +COLOR_GREEN = 2 +COLOR_YELLOW = 3 +COLOR_BLUE = 4 +COLOR_MAGENTA = 5 +COLOR_CYAN = 6 +COLOR_WHITE = 7 A_NORMAL = 0 A_BOLD = 1 @@ -18,9 +18,9 @@ A_STANDOUT = A_REVERSE ATTRMAP = { -A_NORMAL: b"\x1b[0m", -A_BOLD: b"\x1b[1m", # Some terminal emulators don't render bold by default, then use 4m for underline -A_REVERSE: b"\x1b[7m", + A_NORMAL: b"\x1b[0m", + A_BOLD: b"\x1b[1m", # Some terminal emulators don't render bold by default, then use 4m for underline + A_REVERSE: b"\x1b[7m", } # Use http://www.utf8-chartable.de/unicode-utf8-table.pl @@ -55,39 +55,37 @@ KEY_ENTER = 1010 KEY_BACKSPACE = 1011 KEY_DELETE = 1012 -KEY_ESC = 0x1b +KEY_ESC = 0x1B KEY_DC = KEY_DELETE KEY_PPAGE = KEY_PGUP KEY_NPAGE = KEY_PGDN KEYMAP = { -b"\x1b[A": KEY_UP, -b"\x1b[B": KEY_DOWN, -b"\x1b[D": KEY_LEFT, -b"\x1b[C": KEY_RIGHT, -b"\x1bOH": KEY_HOME, -b"\x1bOF": KEY_END, -b"\x1b[1~": KEY_HOME, -b"\x1b[4~": KEY_END, -b"\x1b[5~": KEY_PGUP, -b"\x1b[6~": KEY_PGDN, -b"\x03": KEY_QUIT, -b"\r": KEY_ENTER, -b"\x7f": KEY_BACKSPACE, -b"\x1b[3~": KEY_DELETE, - -b"\x1bOA": KEY_UP, -b"\x1bOB": KEY_DOWN, -b"\x1bOD": KEY_LEFT, -b"\x1bOC": KEY_RIGHT, -b"\x1bOP": KEY_F1, -b"\x1b": KEY_ESC, - -b"\x1b[Z": KEY_BTAB, + b"\x1b[A": KEY_UP, + b"\x1b[B": KEY_DOWN, + b"\x1b[D": KEY_LEFT, + b"\x1b[C": KEY_RIGHT, + b"\x1bOH": KEY_HOME, + b"\x1bOF": KEY_END, + b"\x1b[1~": KEY_HOME, + b"\x1b[4~": KEY_END, + b"\x1b[5~": KEY_PGUP, + b"\x1b[6~": KEY_PGDN, + b"\x03": KEY_QUIT, + b"\r": KEY_ENTER, + b"\x7f": KEY_BACKSPACE, + b"\x1b[3~": KEY_DELETE, + b"\x1bOA": KEY_UP, + b"\x1bOB": KEY_DOWN, + b"\x1bOD": KEY_LEFT, + b"\x1bOC": KEY_RIGHT, + b"\x1bOP": KEY_F1, + b"\x1b": KEY_ESC, + b"\x1b[Z": KEY_BTAB, } -ALL_MOUSE_EVENTS = 0xff +ALL_MOUSE_EVENTS = 0xFF def _wr(s): @@ -96,15 +94,18 @@ def _wr(s): s = bytes(s, "utf-8") os.write(1, s) + def _move(row, col): # TODO: When Python is 3.5, update this to use bytes _wr("\x1b[%d;%dH" % (row + 1, col + 1)) + # Clear specified number of positions def _clear_num_pos(num): if num > 0: _wr("\x1b[%dX" % num) + def _draw_box(left, top, width, height): bottom = top + height - 1 _move(top, left) @@ -132,7 +133,6 @@ class error(Exception): class Window: - def __init__(self, lines, cols, y, x): self.lines = lines self.cols = cols @@ -240,7 +240,7 @@ def getch(self): return -1 key = os.read(0, 32) - if key[0] != 0x1b: + if key[0] != 0x1B: self.keybuf = key self.keyi = 1 key = key[0] @@ -264,63 +264,78 @@ def wrapper(func): endwin() return res + def initscr(): global org_termios org_termios = termios.tcgetattr(0) return SCREEN + def doupdate(): pass + def endwin(): global org_termios _wr(b"\r") termios.tcsetattr(0, termios.TCSANOW, org_termios) + def raw(): tty.setraw(0) + def cbreak(): - #TODO + # TODO pass + def nocbreak(): - #TODO + # TODO pass + def echo(): - #TODO + # TODO pass + def noecho(): - #TODO + # TODO pass + def meta(yes): - #TODO + # TODO pass + def mousemask(mask): # Mouse reporting - X10 compatbility mode _wr(b"\x1b[?9h") + def has_colors(): return False + def can_change_color(): return False + def curs_set(visibility): if visibility > 0: _wr(b"\x1b[?25h") else: _wr(b"\x1b[?25l") + def beep(): _wr(b"\x07") + def newwin(lines, cols, y=0, x=0): - #print("newwin(%d, %d, %d, %d)" % (lines, cols, y, x)) + # print("newwin(%d, %d, %d, %d)" % (lines, cols, y, x)) cols = cols or SCREEN.cols lines = lines or SCREEN.lines return Window(lines, cols, y, x) diff --git a/upip/setup.py b/upip/setup.py deleted file mode 100644 index 3fb55af9e..000000000 --- a/upip/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-upip', - version='1.2.4', - description='Simple package manager for MicroPython.', - long_description='Simple self-hosted package manager for MicroPython (requires usocket, ussl, uzlib, uctypes builtin modules). Compatible only with packages without custom setup.py code.', - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['upip', 'upip_utarfile']) diff --git a/upysh/setup.py b/upysh/setup.py deleted file mode 100644 index 0df07371d..000000000 --- a/upysh/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-upysh', - version='0.6.1', - description='Minimalistic file shell using native Python syntax.', - long_description='Minimalistic file shell using native Python syntax.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['upysh']) diff --git a/urequests/setup.py b/urequests/setup.py deleted file mode 100644 index 43db04aba..000000000 --- a/urequests/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-urequests', - version='0.6', - description='urequests module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['urequests']) diff --git a/urllib.parse/setup.py b/urllib.parse/setup.py deleted file mode 100644 index 72847b4eb..000000000 --- a/urllib.parse/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-urllib.parse', - version='0.5.2', - description='CPython urllib.parse module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['urllib'], - install_requires=['micropython-re-pcre', 'micropython-collections', 'micropython-collections.defaultdict']) diff --git a/urllib.parse/test_urlparse.py b/urllib.parse/test_urlparse.py deleted file mode 100644 index 7689bc119..000000000 --- a/urllib.parse/test_urlparse.py +++ /dev/null @@ -1,855 +0,0 @@ -#! /usr/bin/env python3 - -from test import support -import unittest -import urllib.parse - -RFC1808_BASE = "http://a/b/c/d;p?q#f" -RFC2396_BASE = "http://a/b/c/d;p?q" -RFC3986_BASE = 'http://a/b/c/d;p?q' -SIMPLE_BASE = 'http://a/b/c/d' - -# A list of test cases. Each test case is a two-tuple that contains -# a string with the query and a dictionary with the expected result. - -parse_qsl_test_cases = [ - ("", []), - ("&", []), - ("&&", []), - ("=", [('', '')]), - ("=a", [('', 'a')]), - ("a", [('a', '')]), - ("a=", [('a', '')]), - ("a=", [('a', '')]), - ("&a=b", [('a', 'b')]), - ("a=a+b&b=b+c", [('a', 'a b'), ('b', 'b c')]), - ("a=1&a=2", [('a', '1'), ('a', '2')]), - (b"", []), - (b"&", []), - (b"&&", []), - (b"=", [(b'', b'')]), - (b"=a", [(b'', b'a')]), - (b"a", [(b'a', b'')]), - (b"a=", [(b'a', b'')]), - (b"a=", [(b'a', b'')]), - (b"&a=b", [(b'a', b'b')]), - (b"a=a+b&b=b+c", [(b'a', b'a b'), (b'b', b'b c')]), - (b"a=1&a=2", [(b'a', b'1'), (b'a', b'2')]), -] - -class UrlParseTestCase(unittest.TestCase): - - def checkRoundtrips(self, url, parsed, split): - result = urllib.parse.urlparse(url) - self.assertEqual(result, parsed) - t = (result.scheme, result.netloc, result.path, - result.params, result.query, result.fragment) - self.assertEqual(t, parsed) - # put it back together and it should be the same - result2 = urllib.parse.urlunparse(result) - self.assertEqual(result2, url) - self.assertEqual(result2, result.geturl()) - - # the result of geturl() is a fixpoint; we can always parse it - # again to get the same result: - result3 = urllib.parse.urlparse(result.geturl()) - self.assertEqual(result3.geturl(), result.geturl()) - self.assertEqual(result3, result) - self.assertEqual(result3.scheme, result.scheme) - self.assertEqual(result3.netloc, result.netloc) - self.assertEqual(result3.path, result.path) - self.assertEqual(result3.params, result.params) - self.assertEqual(result3.query, result.query) - self.assertEqual(result3.fragment, result.fragment) - self.assertEqual(result3.username, result.username) - self.assertEqual(result3.password, result.password) - self.assertEqual(result3.hostname, result.hostname) - self.assertEqual(result3.port, result.port) - - # check the roundtrip using urlsplit() as well - result = urllib.parse.urlsplit(url) - self.assertEqual(result, split) - t = (result.scheme, result.netloc, result.path, - result.query, result.fragment) - self.assertEqual(t, split) - result2 = urllib.parse.urlunsplit(result) - self.assertEqual(result2, url) - self.assertEqual(result2, result.geturl()) - - # check the fixpoint property of re-parsing the result of geturl() - result3 = urllib.parse.urlsplit(result.geturl()) - self.assertEqual(result3.geturl(), result.geturl()) - self.assertEqual(result3, result) - self.assertEqual(result3.scheme, result.scheme) - self.assertEqual(result3.netloc, result.netloc) - self.assertEqual(result3.path, result.path) - self.assertEqual(result3.query, result.query) - self.assertEqual(result3.fragment, result.fragment) - self.assertEqual(result3.username, result.username) - self.assertEqual(result3.password, result.password) - self.assertEqual(result3.hostname, result.hostname) - self.assertEqual(result3.port, result.port) - - def test_qsl(self): - for orig, expect in parse_qsl_test_cases: - result = urllib.parse.parse_qsl(orig, keep_blank_values=True) - self.assertEqual(result, expect, "Error parsing %r" % orig) - expect_without_blanks = [v for v in expect if len(v[1])] - result = urllib.parse.parse_qsl(orig, keep_blank_values=False) - self.assertEqual(result, expect_without_blanks, - "Error parsing %r" % orig) - - def test_roundtrips(self): - str_cases = [ - ('file:///tmp/junk.txt', - ('file', '', '/tmp/junk.txt', '', '', ''), - ('file', '', '/tmp/junk.txt', '', '')), - ('imap://mail.python.org/mbox1', - ('imap', 'mail.python.org', '/mbox1', '', '', ''), - ('imap', 'mail.python.org', '/mbox1', '', '')), - ('mms://wms.sys.hinet.net/cts/Drama/09006251100.asf', - ('mms', 'wms.sys.hinet.net', '/cts/Drama/09006251100.asf', - '', '', ''), - ('mms', 'wms.sys.hinet.net', '/cts/Drama/09006251100.asf', - '', '')), - ('nfs://server/path/to/file.txt', - ('nfs', 'server', '/path/to/file.txt', '', '', ''), - ('nfs', 'server', '/path/to/file.txt', '', '')), - ('svn+ssh://svn.zope.org/repos/main/ZConfig/trunk/', - ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', - '', '', ''), - ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', - '', '')), - ('git+ssh://git@github.com/user/project.git', - ('git+ssh', 'git@github.com','/user/project.git', - '','',''), - ('git+ssh', 'git@github.com','/user/project.git', - '', '')), - ] - def _encode(t): - return (t[0].encode('ascii'), - tuple(x.encode('ascii') for x in t[1]), - tuple(x.encode('ascii') for x in t[2])) - bytes_cases = [_encode(x) for x in str_cases] - for url, parsed, split in str_cases + bytes_cases: - self.checkRoundtrips(url, parsed, split) - - def test_http_roundtrips(self): - # urllib.parse.urlsplit treats 'http:' as an optimized special case, - # so we test both 'http:' and 'https:' in all the following. - # Three cheers for white box knowledge! - str_cases = [ - ('://www.python.org', - ('www.python.org', '', '', '', ''), - ('www.python.org', '', '', '')), - ('://www.python.org#abc', - ('www.python.org', '', '', '', 'abc'), - ('www.python.org', '', '', 'abc')), - ('://www.python.org?q=abc', - ('www.python.org', '', '', 'q=abc', ''), - ('www.python.org', '', 'q=abc', '')), - ('://www.python.org/#abc', - ('www.python.org', '/', '', '', 'abc'), - ('www.python.org', '/', '', 'abc')), - ('://a/b/c/d;p?q#f', - ('a', '/b/c/d', 'p', 'q', 'f'), - ('a', '/b/c/d;p', 'q', 'f')), - ] - def _encode(t): - return (t[0].encode('ascii'), - tuple(x.encode('ascii') for x in t[1]), - tuple(x.encode('ascii') for x in t[2])) - bytes_cases = [_encode(x) for x in str_cases] - str_schemes = ('http', 'https') - bytes_schemes = (b'http', b'https') - str_tests = str_schemes, str_cases - bytes_tests = bytes_schemes, bytes_cases - for schemes, test_cases in (str_tests, bytes_tests): - for scheme in schemes: - for url, parsed, split in test_cases: - url = scheme + url - parsed = (scheme,) + parsed - split = (scheme,) + split - self.checkRoundtrips(url, parsed, split) - - def checkJoin(self, base, relurl, expected): - str_components = (base, relurl, expected) - self.assertEqual(urllib.parse.urljoin(base, relurl), expected) - bytes_components = baseb, relurlb, expectedb = [ - x.encode('ascii') for x in str_components] - self.assertEqual(urllib.parse.urljoin(baseb, relurlb), expectedb) - - def test_unparse_parse(self): - str_cases = ['Python', './Python','x-newscheme://foo.com/stuff','x://y','x:/y','x:/','/',] - bytes_cases = [x.encode('ascii') for x in str_cases] - for u in str_cases + bytes_cases: - self.assertEqual(urllib.parse.urlunsplit(urllib.parse.urlsplit(u)), u) - self.assertEqual(urllib.parse.urlunparse(urllib.parse.urlparse(u)), u) - - def test_RFC1808(self): - # "normal" cases from RFC 1808: - self.checkJoin(RFC1808_BASE, 'g:h', 'g:h') - self.checkJoin(RFC1808_BASE, 'g', 'http://a/b/c/g') - self.checkJoin(RFC1808_BASE, './g', 'http://a/b/c/g') - self.checkJoin(RFC1808_BASE, 'g/', 'http://a/b/c/g/') - self.checkJoin(RFC1808_BASE, '/g', 'http://a/g') - self.checkJoin(RFC1808_BASE, '//g', 'http://g') - self.checkJoin(RFC1808_BASE, 'g?y', 'http://a/b/c/g?y') - self.checkJoin(RFC1808_BASE, 'g?y/./x', 'http://a/b/c/g?y/./x') - self.checkJoin(RFC1808_BASE, '#s', 'http://a/b/c/d;p?q#s') - self.checkJoin(RFC1808_BASE, 'g#s', 'http://a/b/c/g#s') - self.checkJoin(RFC1808_BASE, 'g#s/./x', 'http://a/b/c/g#s/./x') - self.checkJoin(RFC1808_BASE, 'g?y#s', 'http://a/b/c/g?y#s') - self.checkJoin(RFC1808_BASE, 'g;x', 'http://a/b/c/g;x') - self.checkJoin(RFC1808_BASE, 'g;x?y#s', 'http://a/b/c/g;x?y#s') - self.checkJoin(RFC1808_BASE, '.', 'http://a/b/c/') - self.checkJoin(RFC1808_BASE, './', 'http://a/b/c/') - self.checkJoin(RFC1808_BASE, '..', 'http://a/b/') - self.checkJoin(RFC1808_BASE, '../', 'http://a/b/') - self.checkJoin(RFC1808_BASE, '../g', 'http://a/b/g') - self.checkJoin(RFC1808_BASE, '../..', 'http://a/') - self.checkJoin(RFC1808_BASE, '../../', 'http://a/') - self.checkJoin(RFC1808_BASE, '../../g', 'http://a/g') - - # "abnormal" cases from RFC 1808: - self.checkJoin(RFC1808_BASE, '', 'http://a/b/c/d;p?q#f') - self.checkJoin(RFC1808_BASE, '../../../g', 'http://a/../g') - self.checkJoin(RFC1808_BASE, '../../../../g', 'http://a/../../g') - self.checkJoin(RFC1808_BASE, '/./g', 'http://a/./g') - self.checkJoin(RFC1808_BASE, '/../g', 'http://a/../g') - self.checkJoin(RFC1808_BASE, 'g.', 'http://a/b/c/g.') - self.checkJoin(RFC1808_BASE, '.g', 'http://a/b/c/.g') - self.checkJoin(RFC1808_BASE, 'g..', 'http://a/b/c/g..') - self.checkJoin(RFC1808_BASE, '..g', 'http://a/b/c/..g') - self.checkJoin(RFC1808_BASE, './../g', 'http://a/b/g') - self.checkJoin(RFC1808_BASE, './g/.', 'http://a/b/c/g/') - self.checkJoin(RFC1808_BASE, 'g/./h', 'http://a/b/c/g/h') - self.checkJoin(RFC1808_BASE, 'g/../h', 'http://a/b/c/h') - - # RFC 1808 and RFC 1630 disagree on these (according to RFC 1808), - # so we'll not actually run these tests (which expect 1808 behavior). - #self.checkJoin(RFC1808_BASE, 'http:g', 'http:g') - #self.checkJoin(RFC1808_BASE, 'http:', 'http:') - - def test_RFC2368(self): - # Issue 11467: path that starts with a number is not parsed correctly - self.assertEqual(urllib.parse.urlparse('mailto:1337@example.org'), - ('mailto', '', '1337@example.org', '', '', '')) - - def test_RFC2396(self): - # cases from RFC 2396 - - - self.checkJoin(RFC2396_BASE, 'g:h', 'g:h') - self.checkJoin(RFC2396_BASE, 'g', 'http://a/b/c/g') - self.checkJoin(RFC2396_BASE, './g', 'http://a/b/c/g') - self.checkJoin(RFC2396_BASE, 'g/', 'http://a/b/c/g/') - self.checkJoin(RFC2396_BASE, '/g', 'http://a/g') - self.checkJoin(RFC2396_BASE, '//g', 'http://g') - self.checkJoin(RFC2396_BASE, 'g?y', 'http://a/b/c/g?y') - self.checkJoin(RFC2396_BASE, '#s', 'http://a/b/c/d;p?q#s') - self.checkJoin(RFC2396_BASE, 'g#s', 'http://a/b/c/g#s') - self.checkJoin(RFC2396_BASE, 'g?y#s', 'http://a/b/c/g?y#s') - self.checkJoin(RFC2396_BASE, 'g;x', 'http://a/b/c/g;x') - self.checkJoin(RFC2396_BASE, 'g;x?y#s', 'http://a/b/c/g;x?y#s') - self.checkJoin(RFC2396_BASE, '.', 'http://a/b/c/') - self.checkJoin(RFC2396_BASE, './', 'http://a/b/c/') - self.checkJoin(RFC2396_BASE, '..', 'http://a/b/') - self.checkJoin(RFC2396_BASE, '../', 'http://a/b/') - self.checkJoin(RFC2396_BASE, '../g', 'http://a/b/g') - self.checkJoin(RFC2396_BASE, '../..', 'http://a/') - self.checkJoin(RFC2396_BASE, '../../', 'http://a/') - self.checkJoin(RFC2396_BASE, '../../g', 'http://a/g') - self.checkJoin(RFC2396_BASE, '', RFC2396_BASE) - self.checkJoin(RFC2396_BASE, '../../../g', 'http://a/../g') - self.checkJoin(RFC2396_BASE, '../../../../g', 'http://a/../../g') - self.checkJoin(RFC2396_BASE, '/./g', 'http://a/./g') - self.checkJoin(RFC2396_BASE, '/../g', 'http://a/../g') - self.checkJoin(RFC2396_BASE, 'g.', 'http://a/b/c/g.') - self.checkJoin(RFC2396_BASE, '.g', 'http://a/b/c/.g') - self.checkJoin(RFC2396_BASE, 'g..', 'http://a/b/c/g..') - self.checkJoin(RFC2396_BASE, '..g', 'http://a/b/c/..g') - self.checkJoin(RFC2396_BASE, './../g', 'http://a/b/g') - self.checkJoin(RFC2396_BASE, './g/.', 'http://a/b/c/g/') - self.checkJoin(RFC2396_BASE, 'g/./h', 'http://a/b/c/g/h') - self.checkJoin(RFC2396_BASE, 'g/../h', 'http://a/b/c/h') - self.checkJoin(RFC2396_BASE, 'g;x=1/./y', 'http://a/b/c/g;x=1/y') - self.checkJoin(RFC2396_BASE, 'g;x=1/../y', 'http://a/b/c/y') - self.checkJoin(RFC2396_BASE, 'g?y/./x', 'http://a/b/c/g?y/./x') - self.checkJoin(RFC2396_BASE, 'g?y/../x', 'http://a/b/c/g?y/../x') - self.checkJoin(RFC2396_BASE, 'g#s/./x', 'http://a/b/c/g#s/./x') - self.checkJoin(RFC2396_BASE, 'g#s/../x', 'http://a/b/c/g#s/../x') - - def test_RFC3986(self): - # Test cases from RFC3986 - self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y') - self.checkJoin(RFC2396_BASE, ';x', 'http://a/b/c/;x') - self.checkJoin(RFC3986_BASE, 'g:h','g:h') - self.checkJoin(RFC3986_BASE, 'g','http://a/b/c/g') - self.checkJoin(RFC3986_BASE, './g','http://a/b/c/g') - self.checkJoin(RFC3986_BASE, 'g/','http://a/b/c/g/') - self.checkJoin(RFC3986_BASE, '/g','http://a/g') - self.checkJoin(RFC3986_BASE, '//g','http://g') - self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y') - self.checkJoin(RFC3986_BASE, 'g?y','http://a/b/c/g?y') - self.checkJoin(RFC3986_BASE, '#s','http://a/b/c/d;p?q#s') - self.checkJoin(RFC3986_BASE, 'g#s','http://a/b/c/g#s') - self.checkJoin(RFC3986_BASE, 'g?y#s','http://a/b/c/g?y#s') - self.checkJoin(RFC3986_BASE, ';x','http://a/b/c/;x') - self.checkJoin(RFC3986_BASE, 'g;x','http://a/b/c/g;x') - self.checkJoin(RFC3986_BASE, 'g;x?y#s','http://a/b/c/g;x?y#s') - self.checkJoin(RFC3986_BASE, '','http://a/b/c/d;p?q') - self.checkJoin(RFC3986_BASE, '.','http://a/b/c/') - self.checkJoin(RFC3986_BASE, './','http://a/b/c/') - self.checkJoin(RFC3986_BASE, '..','http://a/b/') - self.checkJoin(RFC3986_BASE, '../','http://a/b/') - self.checkJoin(RFC3986_BASE, '../g','http://a/b/g') - self.checkJoin(RFC3986_BASE, '../..','http://a/') - self.checkJoin(RFC3986_BASE, '../../','http://a/') - self.checkJoin(RFC3986_BASE, '../../g','http://a/g') - - #Abnormal Examples - - # The 'abnormal scenarios' are incompatible with RFC2986 parsing - # Tests are here for reference. - - #self.checkJoin(RFC3986_BASE, '../../../g','http://a/g') - #self.checkJoin(RFC3986_BASE, '../../../../g','http://a/g') - #self.checkJoin(RFC3986_BASE, '/./g','http://a/g') - #self.checkJoin(RFC3986_BASE, '/../g','http://a/g') - - self.checkJoin(RFC3986_BASE, 'g.','http://a/b/c/g.') - self.checkJoin(RFC3986_BASE, '.g','http://a/b/c/.g') - self.checkJoin(RFC3986_BASE, 'g..','http://a/b/c/g..') - self.checkJoin(RFC3986_BASE, '..g','http://a/b/c/..g') - self.checkJoin(RFC3986_BASE, './../g','http://a/b/g') - self.checkJoin(RFC3986_BASE, './g/.','http://a/b/c/g/') - self.checkJoin(RFC3986_BASE, 'g/./h','http://a/b/c/g/h') - self.checkJoin(RFC3986_BASE, 'g/../h','http://a/b/c/h') - self.checkJoin(RFC3986_BASE, 'g;x=1/./y','http://a/b/c/g;x=1/y') - self.checkJoin(RFC3986_BASE, 'g;x=1/../y','http://a/b/c/y') - self.checkJoin(RFC3986_BASE, 'g?y/./x','http://a/b/c/g?y/./x') - self.checkJoin(RFC3986_BASE, 'g?y/../x','http://a/b/c/g?y/../x') - self.checkJoin(RFC3986_BASE, 'g#s/./x','http://a/b/c/g#s/./x') - self.checkJoin(RFC3986_BASE, 'g#s/../x','http://a/b/c/g#s/../x') - #self.checkJoin(RFC3986_BASE, 'http:g','http:g') # strict parser - self.checkJoin(RFC3986_BASE, 'http:g','http://a/b/c/g') #relaxed parser - - # Test for issue9721 - self.checkJoin('http://a/b/c/de', ';x','http://a/b/c/;x') - - def test_urljoins(self): - self.checkJoin(SIMPLE_BASE, 'g:h','g:h') - self.checkJoin(SIMPLE_BASE, 'http:g','http://a/b/c/g') - self.checkJoin(SIMPLE_BASE, 'http:','http://a/b/c/d') - self.checkJoin(SIMPLE_BASE, 'g','http://a/b/c/g') - self.checkJoin(SIMPLE_BASE, './g','http://a/b/c/g') - self.checkJoin(SIMPLE_BASE, 'g/','http://a/b/c/g/') - self.checkJoin(SIMPLE_BASE, '/g','http://a/g') - self.checkJoin(SIMPLE_BASE, '//g','http://g') - self.checkJoin(SIMPLE_BASE, '?y','http://a/b/c/d?y') - self.checkJoin(SIMPLE_BASE, 'g?y','http://a/b/c/g?y') - self.checkJoin(SIMPLE_BASE, 'g?y/./x','http://a/b/c/g?y/./x') - self.checkJoin(SIMPLE_BASE, '.','http://a/b/c/') - self.checkJoin(SIMPLE_BASE, './','http://a/b/c/') - self.checkJoin(SIMPLE_BASE, '..','http://a/b/') - self.checkJoin(SIMPLE_BASE, '../','http://a/b/') - self.checkJoin(SIMPLE_BASE, '../g','http://a/b/g') - self.checkJoin(SIMPLE_BASE, '../..','http://a/') - self.checkJoin(SIMPLE_BASE, '../../g','http://a/g') - self.checkJoin(SIMPLE_BASE, '../../../g','http://a/../g') - self.checkJoin(SIMPLE_BASE, './../g','http://a/b/g') - self.checkJoin(SIMPLE_BASE, './g/.','http://a/b/c/g/') - self.checkJoin(SIMPLE_BASE, '/./g','http://a/./g') - self.checkJoin(SIMPLE_BASE, 'g/./h','http://a/b/c/g/h') - self.checkJoin(SIMPLE_BASE, 'g/../h','http://a/b/c/h') - self.checkJoin(SIMPLE_BASE, 'http:g','http://a/b/c/g') - self.checkJoin(SIMPLE_BASE, 'http:','http://a/b/c/d') - self.checkJoin(SIMPLE_BASE, 'http:?y','http://a/b/c/d?y') - self.checkJoin(SIMPLE_BASE, 'http:g?y','http://a/b/c/g?y') - self.checkJoin(SIMPLE_BASE, 'http:g?y/./x','http://a/b/c/g?y/./x') - self.checkJoin('http:///', '..','http:///') - self.checkJoin('', 'http://a/b/c/g?y/./x','http://a/b/c/g?y/./x') - self.checkJoin('', 'http://a/./g', 'http://a/./g') - self.checkJoin('svn://pathtorepo/dir1', 'dir2', 'svn://pathtorepo/dir2') - self.checkJoin('svn+ssh://pathtorepo/dir1', 'dir2', 'svn+ssh://pathtorepo/dir2') - - def test_RFC2732(self): - str_cases = [ - ('http://Test.python.org:5432/foo/', 'test.python.org', 5432), - ('http://12.34.56.78:5432/foo/', '12.34.56.78', 5432), - ('http://[::1]:5432/foo/', '::1', 5432), - ('http://[dead:beef::1]:5432/foo/', 'dead:beef::1', 5432), - ('http://[dead:beef::]:5432/foo/', 'dead:beef::', 5432), - ('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]:5432/foo/', - 'dead:beef:cafe:5417:affe:8fa3:deaf:feed', 5432), - ('http://[::12.34.56.78]:5432/foo/', '::12.34.56.78', 5432), - ('http://[::ffff:12.34.56.78]:5432/foo/', - '::ffff:12.34.56.78', 5432), - ('http://Test.python.org/foo/', 'test.python.org', None), - ('http://12.34.56.78/foo/', '12.34.56.78', None), - ('http://[::1]/foo/', '::1', None), - ('http://[dead:beef::1]/foo/', 'dead:beef::1', None), - ('http://[dead:beef::]/foo/', 'dead:beef::', None), - ('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/', - 'dead:beef:cafe:5417:affe:8fa3:deaf:feed', None), - ('http://[::12.34.56.78]/foo/', '::12.34.56.78', None), - ('http://[::ffff:12.34.56.78]/foo/', - '::ffff:12.34.56.78', None), - ] - def _encode(t): - return t[0].encode('ascii'), t[1].encode('ascii'), t[2] - bytes_cases = [_encode(x) for x in str_cases] - for url, hostname, port in str_cases + bytes_cases: - urlparsed = urllib.parse.urlparse(url) - self.assertEqual((urlparsed.hostname, urlparsed.port) , (hostname, port)) - - str_cases = [ - 'http://::12.34.56.78]/', - 'http://[::1/foo/', - 'ftp://[::1/foo/bad]/bad', - 'http://[::1/foo/bad]/bad', - 'http://[::ffff:12.34.56.78'] - bytes_cases = [x.encode('ascii') for x in str_cases] - for invalid_url in str_cases + bytes_cases: - self.assertRaises(ValueError, urllib.parse.urlparse, invalid_url) - - def test_urldefrag(self): - str_cases = [ - ('http://python.org#frag', 'http://python.org', 'frag'), - ('http://python.org', 'http://python.org', ''), - ('http://python.org/#frag', 'http://python.org/', 'frag'), - ('http://python.org/', 'http://python.org/', ''), - ('http://python.org/?q#frag', 'http://python.org/?q', 'frag'), - ('http://python.org/?q', 'http://python.org/?q', ''), - ('http://python.org/p#frag', 'http://python.org/p', 'frag'), - ('http://python.org/p?q', 'http://python.org/p?q', ''), - (RFC1808_BASE, 'http://a/b/c/d;p?q', 'f'), - (RFC2396_BASE, 'http://a/b/c/d;p?q', ''), - ] - def _encode(t): - return type(t)(x.encode('ascii') for x in t) - bytes_cases = [_encode(x) for x in str_cases] - for url, defrag, frag in str_cases + bytes_cases: - result = urllib.parse.urldefrag(url) - self.assertEqual(result.geturl(), url) - self.assertEqual(result, (defrag, frag)) - self.assertEqual(result.url, defrag) - self.assertEqual(result.fragment, frag) - - def test_urlsplit_attributes(self): - url = "HTTP://WWW.PYTHON.ORG/doc/#frag" - p = urllib.parse.urlsplit(url) - self.assertEqual(p.scheme, "http") - self.assertEqual(p.netloc, "WWW.PYTHON.ORG") - self.assertEqual(p.path, "/doc/") - self.assertEqual(p.query, "") - self.assertEqual(p.fragment, "frag") - self.assertEqual(p.username, None) - self.assertEqual(p.password, None) - self.assertEqual(p.hostname, "www.python.org") - self.assertEqual(p.port, None) - # geturl() won't return exactly the original URL in this case - # since the scheme is always case-normalized - # We handle this by ignoring the first 4 characters of the URL - self.assertEqual(p.geturl()[4:], url[4:]) - - url = "http://User:Pass@www.python.org:080/doc/?query=yes#frag" - p = urllib.parse.urlsplit(url) - self.assertEqual(p.scheme, "http") - self.assertEqual(p.netloc, "User:Pass@www.python.org:080") - self.assertEqual(p.path, "/doc/") - self.assertEqual(p.query, "query=yes") - self.assertEqual(p.fragment, "frag") - self.assertEqual(p.username, "User") - self.assertEqual(p.password, "Pass") - self.assertEqual(p.hostname, "www.python.org") - self.assertEqual(p.port, 80) - self.assertEqual(p.geturl(), url) - - # Addressing issue1698, which suggests Username can contain - # "@" characters. Though not RFC compliant, many ftp sites allow - # and request email addresses as usernames. - - url = "http://User@example.com:Pass@www.python.org:080/doc/?query=yes#frag" - p = urllib.parse.urlsplit(url) - self.assertEqual(p.scheme, "http") - self.assertEqual(p.netloc, "User@example.com:Pass@www.python.org:080") - self.assertEqual(p.path, "/doc/") - self.assertEqual(p.query, "query=yes") - self.assertEqual(p.fragment, "frag") - self.assertEqual(p.username, "User@example.com") - self.assertEqual(p.password, "Pass") - self.assertEqual(p.hostname, "www.python.org") - self.assertEqual(p.port, 80) - self.assertEqual(p.geturl(), url) - - # And check them all again, only with bytes this time - url = b"HTTP://WWW.PYTHON.ORG/doc/#frag" - p = urllib.parse.urlsplit(url) - self.assertEqual(p.scheme, b"http") - self.assertEqual(p.netloc, b"WWW.PYTHON.ORG") - self.assertEqual(p.path, b"/doc/") - self.assertEqual(p.query, b"") - self.assertEqual(p.fragment, b"frag") - self.assertEqual(p.username, None) - self.assertEqual(p.password, None) - self.assertEqual(p.hostname, b"www.python.org") - self.assertEqual(p.port, None) - self.assertEqual(p.geturl()[4:], url[4:]) - - url = b"http://User:Pass@www.python.org:080/doc/?query=yes#frag" - p = urllib.parse.urlsplit(url) - self.assertEqual(p.scheme, b"http") - self.assertEqual(p.netloc, b"User:Pass@www.python.org:080") - self.assertEqual(p.path, b"/doc/") - self.assertEqual(p.query, b"query=yes") - self.assertEqual(p.fragment, b"frag") - self.assertEqual(p.username, b"User") - self.assertEqual(p.password, b"Pass") - self.assertEqual(p.hostname, b"www.python.org") - self.assertEqual(p.port, 80) - self.assertEqual(p.geturl(), url) - - url = b"http://User@example.com:Pass@www.python.org:080/doc/?query=yes#frag" - p = urllib.parse.urlsplit(url) - self.assertEqual(p.scheme, b"http") - self.assertEqual(p.netloc, b"User@example.com:Pass@www.python.org:080") - self.assertEqual(p.path, b"/doc/") - self.assertEqual(p.query, b"query=yes") - self.assertEqual(p.fragment, b"frag") - self.assertEqual(p.username, b"User@example.com") - self.assertEqual(p.password, b"Pass") - self.assertEqual(p.hostname, b"www.python.org") - self.assertEqual(p.port, 80) - self.assertEqual(p.geturl(), url) - - # Verify an illegal port is returned as None - url = b"HTTP://WWW.PYTHON.ORG:65536/doc/#frag" - p = urllib.parse.urlsplit(url) - self.assertEqual(p.port, None) - - def test_attributes_bad_port(self): - """Check handling of non-integer ports.""" - p = urllib.parse.urlsplit("http://www.example.net:foo") - self.assertEqual(p.netloc, "www.example.net:foo") - self.assertRaises(ValueError, lambda: p.port) - - p = urllib.parse.urlparse("http://www.example.net:foo") - self.assertEqual(p.netloc, "www.example.net:foo") - self.assertRaises(ValueError, lambda: p.port) - - # Once again, repeat ourselves to test bytes - p = urllib.parse.urlsplit(b"http://www.example.net:foo") - self.assertEqual(p.netloc, b"www.example.net:foo") - self.assertRaises(ValueError, lambda: p.port) - - p = urllib.parse.urlparse(b"http://www.example.net:foo") - self.assertEqual(p.netloc, b"www.example.net:foo") - self.assertRaises(ValueError, lambda: p.port) - - def test_attributes_without_netloc(self): - # This example is straight from RFC 3261. It looks like it - # should allow the username, hostname, and port to be filled - # in, but doesn't. Since it's a URI and doesn't use the - # scheme://netloc syntax, the netloc and related attributes - # should be left empty. - uri = "sip:alice@atlanta.com;maddr=239.255.255.1;ttl=15" - p = urllib.parse.urlsplit(uri) - self.assertEqual(p.netloc, "") - self.assertEqual(p.username, None) - self.assertEqual(p.password, None) - self.assertEqual(p.hostname, None) - self.assertEqual(p.port, None) - self.assertEqual(p.geturl(), uri) - - p = urllib.parse.urlparse(uri) - self.assertEqual(p.netloc, "") - self.assertEqual(p.username, None) - self.assertEqual(p.password, None) - self.assertEqual(p.hostname, None) - self.assertEqual(p.port, None) - self.assertEqual(p.geturl(), uri) - - # You guessed it, repeating the test with bytes input - uri = b"sip:alice@atlanta.com;maddr=239.255.255.1;ttl=15" - p = urllib.parse.urlsplit(uri) - self.assertEqual(p.netloc, b"") - self.assertEqual(p.username, None) - self.assertEqual(p.password, None) - self.assertEqual(p.hostname, None) - self.assertEqual(p.port, None) - self.assertEqual(p.geturl(), uri) - - p = urllib.parse.urlparse(uri) - self.assertEqual(p.netloc, b"") - self.assertEqual(p.username, None) - self.assertEqual(p.password, None) - self.assertEqual(p.hostname, None) - self.assertEqual(p.port, None) - self.assertEqual(p.geturl(), uri) - - def test_noslash(self): - # Issue 1637: http://foo.com?query is legal - self.assertEqual(urllib.parse.urlparse("http://example.com?blahblah=/foo"), - ('http', 'example.com', '', '', 'blahblah=/foo', '')) - self.assertEqual(urllib.parse.urlparse(b"http://example.com?blahblah=/foo"), - (b'http', b'example.com', b'', b'', b'blahblah=/foo', b'')) - - def test_withoutscheme(self): - # Test urlparse without scheme - # Issue 754016: urlparse goes wrong with IP:port without scheme - # RFC 1808 specifies that netloc should start with //, urlparse expects - # the same, otherwise it classifies the portion of url as path. - self.assertEqual(urllib.parse.urlparse("path"), - ('','','path','','','')) - self.assertEqual(urllib.parse.urlparse("//www.python.org:80"), - ('','www.python.org:80','','','','')) - self.assertEqual(urllib.parse.urlparse("http://www.python.org:80"), - ('http','www.python.org:80','','','','')) - # Repeat for bytes input - self.assertEqual(urllib.parse.urlparse(b"path"), - (b'',b'',b'path',b'',b'',b'')) - self.assertEqual(urllib.parse.urlparse(b"//www.python.org:80"), - (b'',b'www.python.org:80',b'',b'',b'',b'')) - self.assertEqual(urllib.parse.urlparse(b"http://www.python.org:80"), - (b'http',b'www.python.org:80',b'',b'',b'',b'')) - - def test_portseparator(self): - # Issue 754016 makes changes for port separator ':' from scheme separator - self.assertEqual(urllib.parse.urlparse("path:80"), - ('','','path:80','','','')) - self.assertEqual(urllib.parse.urlparse("http:"),('http','','','','','')) - self.assertEqual(urllib.parse.urlparse("https:"),('https','','','','','')) - self.assertEqual(urllib.parse.urlparse("http://www.python.org:80"), - ('http','www.python.org:80','','','','')) - # As usual, need to check bytes input as well - self.assertEqual(urllib.parse.urlparse(b"path:80"), - (b'',b'',b'path:80',b'',b'',b'')) - self.assertEqual(urllib.parse.urlparse(b"http:"),(b'http',b'',b'',b'',b'',b'')) - self.assertEqual(urllib.parse.urlparse(b"https:"),(b'https',b'',b'',b'',b'',b'')) - self.assertEqual(urllib.parse.urlparse(b"http://www.python.org:80"), - (b'http',b'www.python.org:80',b'',b'',b'',b'')) - - def test_usingsys(self): - # Issue 3314: sys module is used in the error - self.assertRaises(TypeError, urllib.parse.urlencode, "foo") - - def test_anyscheme(self): - # Issue 7904: s3://foo.com/stuff has netloc "foo.com". - self.assertEqual(urllib.parse.urlparse("s3://foo.com/stuff"), - ('s3', 'foo.com', '/stuff', '', '', '')) - self.assertEqual(urllib.parse.urlparse("x-newscheme://foo.com/stuff"), - ('x-newscheme', 'foo.com', '/stuff', '', '', '')) - self.assertEqual(urllib.parse.urlparse("x-newscheme://foo.com/stuff?query#fragment"), - ('x-newscheme', 'foo.com', '/stuff', '', 'query', 'fragment')) - self.assertEqual(urllib.parse.urlparse("x-newscheme://foo.com/stuff?query"), - ('x-newscheme', 'foo.com', '/stuff', '', 'query', '')) - - # And for bytes... - self.assertEqual(urllib.parse.urlparse(b"s3://foo.com/stuff"), - (b's3', b'foo.com', b'/stuff', b'', b'', b'')) - self.assertEqual(urllib.parse.urlparse(b"x-newscheme://foo.com/stuff"), - (b'x-newscheme', b'foo.com', b'/stuff', b'', b'', b'')) - self.assertEqual(urllib.parse.urlparse(b"x-newscheme://foo.com/stuff?query#fragment"), - (b'x-newscheme', b'foo.com', b'/stuff', b'', b'query', b'fragment')) - self.assertEqual(urllib.parse.urlparse(b"x-newscheme://foo.com/stuff?query"), - (b'x-newscheme', b'foo.com', b'/stuff', b'', b'query', b'')) - - def _test_mixed_types_rejected(self): - # Several functions that process either strings or ASCII encoded bytes - # accept multiple arguments. Check they reject mixed type input - with self.assertRaisesRegex(TypeError, "Cannot mix str"): - urllib.parse.urlparse("www.python.org", b"http") - with self.assertRaisesRegex(TypeError, "Cannot mix str"): - urllib.parse.urlparse(b"www.python.org", "http") - with self.assertRaisesRegex(TypeError, "Cannot mix str"): - urllib.parse.urlsplit("www.python.org", b"http") - with self.assertRaisesRegex(TypeError, "Cannot mix str"): - urllib.parse.urlsplit(b"www.python.org", "http") - with self.assertRaisesRegex(TypeError, "Cannot mix str"): - urllib.parse.urlunparse(( b"http", "www.python.org","","","","")) - with self.assertRaisesRegex(TypeError, "Cannot mix str"): - urllib.parse.urlunparse(("http", b"www.python.org","","","","")) - with self.assertRaisesRegex(TypeError, "Cannot mix str"): - urllib.parse.urlunsplit((b"http", "www.python.org","","","")) - with self.assertRaisesRegex(TypeError, "Cannot mix str"): - urllib.parse.urlunsplit(("http", b"www.python.org","","","")) - with self.assertRaisesRegex(TypeError, "Cannot mix str"): - urllib.parse.urljoin("http://python.org", b"http://python.org") - with self.assertRaisesRegex(TypeError, "Cannot mix str"): - urllib.parse.urljoin(b"http://python.org", "http://python.org") - - def _check_result_type(self, str_type, num_args): -# num_args = len(str_type._fields) - bytes_type = str_type._encoded_counterpart - self.assertIs(bytes_type._decoded_counterpart, str_type) - str_args = ('',) * num_args - bytes_args = (b'',) * num_args - str_result = str_type(*str_args) - bytes_result = bytes_type(*bytes_args) - encoding = 'ascii' - errors = 'strict' - self.assertEqual(str_result, str_args) - self.assertEqual(bytes_result.decode(), str_args) - self.assertEqual(bytes_result.decode(), str_result) - self.assertEqual(bytes_result.decode(encoding), str_args) - self.assertEqual(bytes_result.decode(encoding), str_result) - self.assertEqual(bytes_result.decode(encoding, errors), str_args) - self.assertEqual(bytes_result.decode(encoding, errors), str_result) - self.assertEqual(bytes_result, bytes_args) - self.assertEqual(str_result.encode(), bytes_args) - self.assertEqual(str_result.encode(), bytes_result) - self.assertEqual(str_result.encode(encoding), bytes_args) - self.assertEqual(str_result.encode(encoding), bytes_result) - self.assertEqual(str_result.encode(encoding, errors), bytes_args) - self.assertEqual(str_result.encode(encoding, errors), bytes_result) - - def test_result_pairs(self): - # Check encoding and decoding between result pairs - result_types = [ - (urllib.parse.DefragResult, 2), - (urllib.parse.SplitResult, 5), - (urllib.parse.ParseResult, 6), - ] - for result_type in result_types: - self._check_result_type(*result_type) - - def _test_parse_qs_encoding(self): - result = urllib.parse.parse_qs("key=\u0141%E9", encoding="latin-1") - self.assertEqual(result, {'key': ['\u0141\xE9']}) - result = urllib.parse.parse_qs("key=\u0141%C3%A9", encoding="utf-8") - self.assertEqual(result, {'key': ['\u0141\xE9']}) - result = urllib.parse.parse_qs("key=\u0141%C3%A9", encoding="ascii") - self.assertEqual(result, {'key': ['\u0141\ufffd\ufffd']}) - result = urllib.parse.parse_qs("key=\u0141%E9-", encoding="ascii") - self.assertEqual(result, {'key': ['\u0141\ufffd-']}) - result = urllib.parse.parse_qs("key=\u0141%E9-", encoding="ascii", - errors="ignore") - self.assertEqual(result, {'key': ['\u0141-']}) - - def _test_parse_qsl_encoding(self): - result = urllib.parse.parse_qsl("key=\u0141%E9", encoding="latin-1") - self.assertEqual(result, [('key', '\u0141\xE9')]) - result = urllib.parse.parse_qsl("key=\u0141%C3%A9", encoding="utf-8") - self.assertEqual(result, [('key', '\u0141\xE9')]) - result = urllib.parse.parse_qsl("key=\u0141%C3%A9", encoding="ascii") - self.assertEqual(result, [('key', '\u0141\ufffd\ufffd')]) - result = urllib.parse.parse_qsl("key=\u0141%E9-", encoding="ascii") - self.assertEqual(result, [('key', '\u0141\ufffd-')]) - result = urllib.parse.parse_qsl("key=\u0141%E9-", encoding="ascii", - errors="ignore") - self.assertEqual(result, [('key', '\u0141-')]) - - def test_splitnport(self): - # Normal cases are exercised by other tests; ensure that we also - # catch cases with no port specified. (testcase ensuring coverage) - result = urllib.parse.splitnport('parrot:88') - self.assertEqual(result, ('parrot', 88)) - result = urllib.parse.splitnport('parrot') - self.assertEqual(result, ('parrot', -1)) - result = urllib.parse.splitnport('parrot', 55) - self.assertEqual(result, ('parrot', 55)) - result = urllib.parse.splitnport('parrot:') - self.assertEqual(result, ('parrot', None)) - - def test_splitquery(self): - # Normal cases are exercised by other tests; ensure that we also - # catch cases with no port specified (testcase ensuring coverage) - result = urllib.parse.splitquery('http://python.org/fake?foo=bar') - self.assertEqual(result, ('http://python.org/fake', 'foo=bar')) - result = urllib.parse.splitquery('http://python.org/fake?foo=bar?') - self.assertEqual(result, ('http://python.org/fake?foo=bar', '')) - result = urllib.parse.splitquery('http://python.org/fake') - self.assertEqual(result, ('http://python.org/fake', None)) - - def test_splitvalue(self): - # Normal cases are exercised by other tests; test pathological cases - # with no key/value pairs. (testcase ensuring coverage) - result = urllib.parse.splitvalue('foo=bar') - self.assertEqual(result, ('foo', 'bar')) - result = urllib.parse.splitvalue('foo=') - self.assertEqual(result, ('foo', '')) - result = urllib.parse.splitvalue('foobar') - self.assertEqual(result, ('foobar', None)) - - def test_to_bytes(self): - result = urllib.parse.to_bytes('http://www.python.org') - self.assertEqual(result, 'http://www.python.org') -# self.assertRaises(UnicodeError, urllib.parse.to_bytes, -# 'http://www.python.org/medi\u00e6val') - - def test_urlencode_sequences(self): - # Other tests incidentally urlencode things; test non-covered cases: - # Sequence and object values. - result = urllib.parse.urlencode({'a': [1, 2], 'b': (3, 4, 5)}, True) - # we cannot rely on ordering here - assert set(result.split('&')) == {'a=1', 'a=2', 'b=3', 'b=4', 'b=5'} - - class Trivial: - def __str__(self): - return 'trivial' - - result = urllib.parse.urlencode({'a': Trivial()}, True) - self.assertEqual(result, 'a=trivial') - - def test_quote_from_bytes(self): - self.assertRaises(TypeError, urllib.parse.quote_from_bytes, 'foo') - result = urllib.parse.quote_from_bytes(b'archaeological arcana') - self.assertEqual(result, 'archaeological%20arcana') - result = urllib.parse.quote_from_bytes(b'') - self.assertEqual(result, '') - - def test_unquote_to_bytes(self): - result = urllib.parse.unquote_to_bytes('abc%20def') - self.assertEqual(result, b'abc def') - result = urllib.parse.unquote_to_bytes('') - self.assertEqual(result, b'') - - def test_quote_errors(self): - self.assertRaises(TypeError, urllib.parse.quote, b'foo', - encoding='utf-8') - self.assertRaises(TypeError, urllib.parse.quote, b'foo', errors='strict') - - def test_issue14072(self): - p1 = urllib.parse.urlsplit('tel:+31-641044153') - self.assertEqual(p1.scheme, 'tel') - self.assertEqual(p1.path, '+31-641044153') - p2 = urllib.parse.urlsplit('tel:+31641044153') - self.assertEqual(p2.scheme, 'tel') - self.assertEqual(p2.path, '+31641044153') - # assert the behavior for urlparse - p1 = urllib.parse.urlparse('tel:+31-641044153') - self.assertEqual(p1.scheme, 'tel') - self.assertEqual(p1.path, '+31-641044153') - p2 = urllib.parse.urlparse('tel:+31641044153') - self.assertEqual(p2.scheme, 'tel') - self.assertEqual(p2.path, '+31641044153') - - def test_telurl_params(self): - p1 = urllib.parse.urlparse('tel:123-4;phone-context=+1-650-516') - self.assertEqual(p1.scheme, 'tel') - self.assertEqual(p1.path, '123-4') - self.assertEqual(p1.params, 'phone-context=+1-650-516') - - p1 = urllib.parse.urlparse('tel:+1-201-555-0123') - self.assertEqual(p1.scheme, 'tel') - self.assertEqual(p1.path, '+1-201-555-0123') - self.assertEqual(p1.params, '') - - p1 = urllib.parse.urlparse('tel:7042;phone-context=example.com') - self.assertEqual(p1.scheme, 'tel') - self.assertEqual(p1.path, '7042') - self.assertEqual(p1.params, 'phone-context=example.com') - - p1 = urllib.parse.urlparse('tel:863-1234;phone-context=+1-914-555') - self.assertEqual(p1.scheme, 'tel') - self.assertEqual(p1.path, '863-1234') - self.assertEqual(p1.params, 'phone-context=+1-914-555') - - -def test_main(): - support.run_unittest(UrlParseTestCase) - -if __name__ == "__main__": - test_main() diff --git a/urllib.urequest/setup.py b/urllib.urequest/setup.py deleted file mode 100644 index 8612316a3..000000000 --- a/urllib.urequest/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-urllib.urequest', - version='0.6', - description='urllib.urequest module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - packages=['urllib']) diff --git a/urllib/setup.py b/urllib/setup.py deleted file mode 100644 index 1e2257bd8..000000000 --- a/urllib/setup.py +++ /dev/null @@ -1,18 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise distutils will peek up our -# module instead of system one. -sys.path.pop(0) -sys.path.insert(0, '..') -from setuptools import setup -import metadata - -NAME = 'urllib' - -setup(name='micropython-' + NAME, - version='0.0.0', - description=metadata.desc_dummy(NAME), - url=metadata.url, - author=metadata.author_upy_devels, - author_email=metadata.author_upy_devels_email, - license='MIT', - py_modules=[NAME]) diff --git a/urllib/urllib.py b/urllib/urllib.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/utarfile/setup.py b/utarfile/setup.py deleted file mode 100644 index 3c3f06648..000000000 --- a/utarfile/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-utarfile', - version='0.3.2', - description='utarfile module for MicroPython', - long_description='Lightweight tarfile module subset', - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['utarfile']) diff --git a/uu/setup.py b/uu/setup.py deleted file mode 100644 index ecae47a14..000000000 --- a/uu/setup.py +++ /dev/null @@ -1,21 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-uu', - version='0.5.1', - description='CPython uu module ported to MicroPython', - long_description='This is a module ported from CPython standard library to be compatible with\nMicroPython interpreter. Usually, this means applying small patches for\nfeatures not supported (yet, or at all) in MicroPython. Sometimes, heavier\nchanges are required. Note that CPython modules are written with availability\nof vast resources in mind, and may not work for MicroPython ports with\nlimited heap. If you are affected by such a case, please help reimplement\nthe module from scratch.', - url='https://github.com/micropython/micropython-lib', - author='CPython Developers', - author_email='python-dev@python.org', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='Python', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['uu'], - install_requires=['micropython-binascii', 'micropython-os']) diff --git a/uuid/metadata.txt b/uuid/metadata.txt deleted file mode 100644 index abee00b44..000000000 --- a/uuid/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.1 diff --git a/uuid/setup.py b/uuid/setup.py deleted file mode 100644 index e498b8e63..000000000 --- a/uuid/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-uuid', - version='0.0.1', - description='Dummy uuid module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['uuid']) diff --git a/uuid/uuid.py b/uuid/uuid.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/venv/metadata.txt b/venv/metadata.txt deleted file mode 100644 index 976088c8a..000000000 --- a/venv/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.0 diff --git a/venv/setup.py b/venv/setup.py deleted file mode 100644 index 230747c53..000000000 --- a/venv/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-venv', - version='0.0.0', - description='Dummy venv module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['venv']) diff --git a/venv/venv.py b/venv/venv.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/warnings/example_warn.py b/warnings/example_warn.py deleted file mode 100644 index fb032971c..000000000 --- a/warnings/example_warn.py +++ /dev/null @@ -1,6 +0,0 @@ -import warnings - -warnings.warn('block_size of %d seems too small; using our ' - 'default of %d.', - RuntimeError, 2) -# RuntimeWarning, 2) diff --git a/warnings/setup.py b/warnings/setup.py deleted file mode 100644 index e2771c2e3..000000000 --- a/warnings/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-warnings', - version='0.1.1', - description='warnings module for MicroPython', - long_description="This is a module reimplemented specifically for MicroPython standard library,\nwith efficient and lean design in mind. Note that this module is likely work\nin progress and likely supports just a subset of CPython's corresponding\nmodule. Please help with the development if you are interested in this\nmodule.", - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['warnings']) diff --git a/weakref/metadata.txt b/weakref/metadata.txt deleted file mode 100644 index fda992a9c..000000000 --- a/weakref/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype=dummy -type=module -version = 0.0.2 diff --git a/weakref/setup.py b/weakref/setup.py deleted file mode 100644 index 822d4787f..000000000 --- a/weakref/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-weakref', - version='0.0.2', - description='Dummy weakref module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['weakref']) diff --git a/weakref/weakref.py b/weakref/weakref.py deleted file mode 100644 index 76aabfa31..000000000 --- a/weakref/weakref.py +++ /dev/null @@ -1,7 +0,0 @@ -# -# This is completely dummy implementation, which does not -# provide real weak references, and thus will hoard memory! -# - -def proxy(obj, cb=None): - return obj diff --git a/xmltok/setup.py b/xmltok/setup.py deleted file mode 100644 index 4a12005ef..000000000 --- a/xmltok/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-xmltok', - version='0.2', - description='xmltok module for MicroPython', - long_description='Simple XML tokenizer', - url='https://github.com/micropython/micropython-lib', - author='Paul Sokolovsky', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['xmltok']) diff --git a/xmltok/test_xmltok.py b/xmltok/test_xmltok.py deleted file mode 100644 index 2f5afe9fa..000000000 --- a/xmltok/test_xmltok.py +++ /dev/null @@ -1,25 +0,0 @@ -import xmltok - -expected = [ -('PI', 'xml'), -('ATTR', ('', 'version'), '1.0'), -('START_TAG', ('s', 'Envelope')), -('ATTR', ('xmlns', 's'), 'http://schemas.xmlsoap.org/soap/envelope/'), -('ATTR', ('s', 'encodingStyle'), 'http://schemas.xmlsoap.org/soap/encoding/'), -('START_TAG', ('s', 'Body')), -('START_TAG', ('u', 'GetConnectionTypeInfo')), -('ATTR', ('xmlns', 'u'), 'urn:schemas-upnp-org:service:WANIPConnection:1'), -('TEXT', 'foo bar\n baz\n \n'), -('END_TAG', ('u', 'GetConnectionTypeInfo')), -('END_TAG', ('s', 'Body')), -('END_TAG', ('s', 'Envelope')), -] - -dir = "." -if "/" in __file__: - dir = __file__.rsplit("/", 1)[0] - -ex = iter(expected) -for i in xmltok.tokenize(open(dir + "/test.xml")): - #print(i) - assert i == next(ex) diff --git a/zipfile/metadata.txt b/zipfile/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/zipfile/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/zipfile/setup.py b/zipfile/setup.py deleted file mode 100644 index 7c7e4117b..000000000 --- a/zipfile/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-zipfile', - version='0.0.1', - description='Dummy zipfile module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['zipfile']) diff --git a/zipfile/zipfile.py b/zipfile/zipfile.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/zlib/metadata.txt b/zlib/metadata.txt deleted file mode 100644 index dc5f60a66..000000000 --- a/zlib/metadata.txt +++ /dev/null @@ -1,3 +0,0 @@ -srctype = dummy -type = module -version = 0.0.1 diff --git a/zlib/setup.py b/zlib/setup.py deleted file mode 100644 index a5584b1f3..000000000 --- a/zlib/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -import sys -# Remove current dir from sys.path, otherwise setuptools will peek up our -# module instead of system's. -sys.path.pop(0) -from setuptools import setup -sys.path.append("..") -import sdist_upip - -setup(name='micropython-zlib', - version='0.0.1', - description='Dummy zlib module for MicroPython', - long_description='This is a dummy implementation of a module for MicroPython standard library.\nIt contains zero or very little functionality, and primarily intended to\navoid import errors (using idea that even if an application imports a\nmodule, it may be not using it onevery code path, so may work at least\npartially). It is expected that more complete implementation of the module\nwill be provided later. Please help with the development if you are\ninterested in this module.', - url='https://github.com/micropython/micropython-lib', - author='micropython-lib Developers', - author_email='micro-python@googlegroups.com', - maintainer='micropython-lib Developers', - maintainer_email='micro-python@googlegroups.com', - license='MIT', - cmdclass={'sdist': sdist_upip.sdist}, - py_modules=['zlib']) diff --git a/zlib/zlib.py b/zlib/zlib.py deleted file mode 100644 index e803341cd..000000000 --- a/zlib/zlib.py +++ /dev/null @@ -1 +0,0 @@ -from uzlib import *