Search code examples
pythonpython-3.xpython-reraspberry-pi-picothonny

MicroPython application throws AttributeError for very basic use of re.split without a duplicate "re.py" file present


I don't seem to understand why my rather generic use of the split function from the re library is failing:

from machine import Pin, SPI, UART
from array import array
import sys, re, time, math, framebuf

sys.path.append("C:/Source/Pico/SSD1322_SPI_4W")
print(sys.path)
import ssd1322

print("Test print")
s1="123\t123\t123"
s2 = re.split(r'\t', s1)
print(s2)

The output produced is as follows:

MicroPython v1.19.1 on 2022-06-18; Raspberry Pi Pico with RP2040 Type "help()" for more information.
%Run -c $EDITOR_CONTENT ['', '.frozen', '/lib', 'C:/Source/Pico/SSD1322_SPI_4W']

Test print

Traceback (most recent call last): File "", line 67, in AttributeError: 'module' object has no attribute 'split'

This script is developed for MicroPython v1.19.1 (Thonny 3.3.13 running Python 3.7.9) on a Win7 machine used to connect and deploy to a Raspberry Pi Pico (RP2040). I pared down the source to the least amount of code that would still reproduce the issue, but felt I ought to leave my imports incase the issue could be a library redundantly calling another library. I am fairly new to both Python and the Pico, so I'm probably just being ignorant of something basic and essential here. Someone in the comments here asked about creating another module/file "re.py" that would cause the script to attempt to use this instead, but I don't see such a file in the program directory.

Additionally, I have tried alternatives to the split line:

s2 = re.split(r"[^a-zA-Z0-9_]+", s1)

s2 = re.split(r"[\W]+", s1)

...but both provide the same result.

Thanks


Solution

  • In Micropython, you need to compile the matching pattern and then call the split method on the returned regex object.

    import re
    
    
    s1="123\t123\t123"
    pattern = re.compile(r'\t')
    s2 = pattern.split(s1)