{"id":20442279,"url":"https://github.com/patbeirne/tf","last_synced_at":"2025-04-12T23:33:54.279Z","repository":{"id":200307527,"uuid":"350920319","full_name":"patbeirne/tf","owner":"patbeirne","description":"TF is a module for MicroPython to help manage files in the local flash file system of the embedded CPU. It provides methods for file copy, search and edit. It also provides a trivial shell prompt for file manipulations (copy/move/delete, sub-directory create/rename/delete/chdir) and file examination (cat/grep/sed).  All methods are stream-based, so they can handle large files, like debug listings or log files.","archived":false,"fork":false,"pushed_at":"2023-10-15T12:45:55.000Z","size":68,"stargazers_count":4,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-12T23:33:46.649Z","etag":null,"topics":["esp8266","micropython"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/patbeirne.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-03-24T02:22:58.000Z","updated_at":"2023-10-15T12:46:00.000Z","dependencies_parsed_at":null,"dependency_job_id":"dfc40945-08e0-4b0d-a581-67a1deb7d252","html_url":"https://github.com/patbeirne/tf","commit_stats":null,"previous_names":["patbeirne/tf"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/patbeirne%2Ftf","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/patbeirne%2Ftf/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/patbeirne%2Ftf/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/patbeirne%2Ftf/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/patbeirne","download_url":"https://codeload.github.com/patbeirne/tf/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248647259,"owners_count":21139081,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["esp8266","micropython"],"created_at":"2024-11-15T09:39:01.269Z","updated_at":"2025-04-12T23:33:54.273Z","avatar_url":"https://github.com/patbeirne.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# TF\n\nA module for manipulating **T**ext **F**iles in the *MicroPython* environment.  \n\n[TOC]\n\n#### TL;DR\nA small app for the *MicroPython* board environment, to allow easy access to text files stored in the local flash file system.\n\n*Tested on **1.21** and everything works properly*\n\n## Oveview\n\nI discovered *MicroPython* when working on the ESP8266 processor. Everything seemed very nice, except it was awkward moving files around. All the methods I could find required a back-and-forth with the programmer's desktop.\n\nThis **TF** module simulates a command shell and gives you the ability to copy, move and delete files. It includes commands for searching, editing and making backups of local text files, using only the embedded processor. The module itself is small (about 7k) and can be downloaded into the target machine. Once there, the user can invoke the command line, or simply call the functions from Python.\n\nFor example, to make a backup of a file from your Python app, you can call  \n\n```\n    tf.cp('log.txt','log.2021-03-20.bak')\n```\n\nor you can use the builtin command line and\n\n```\n/$ cp mail.log m.log.bak\n/$ dir\n-rwx all       230 boot.py\n-rwx all      2886 m.log.bak\n-rwx all      2886 mail.log\n-rwx all      2401 main.py\n-rwx all      2259 main_test.py\n-rwx all     99182 mqtt.log\n-rwx all      6949 tf.py\n-rwx all        15 webrepl_cfg.py\ndisk size:     392 KB   disk free: 196 KB\n\n/$ cat -n -l 1000-1005 mqtt.log\n====mqtt.log=====\n1000 1616120701: Client mosq-d911rjWHX3Rdwcntoo disconnected.\n1001 1616124181: New connection from 72.53.209.21 on port 1883.\n1002 1616124181: New client connected from 72.53.209.21 as mosq-kwcmiGmZ7jlEVRecrU (c1, k60).\n1003 1616124181: Client mosq-kwcmiGmZ7jlEVRecrU disconnected.\n1004 1616126374: Socket error on client DVES_98843E, disconnecting.\n1005 1616126425: Client DVES_83244E has exceeded timeout, disconnecting.\n\n/$ grep 24.114.80.\\d+ mqtt.log\n977 1616120273: New connection from 24.114.80.91 on port 1883.\n980 1616120273: New client connected from 24.114.80.91 as Rutherford1616120233590 (c1, k60, u'patb').\n1046 1616142039: New connection from 24.114.80.109 on port 1883.\n1049 1616142039: New client connected from 24.114.80.109 as Rutherford1616120233590 (c1, k60, u'patb').\n\n/$ \n```\nUses:\n\n* make a backup copy of a file\n* examine and clean up your filesystem and its directories\n* scan a mega-byte log file for entries using the `grep`(search) or `sed` (search-and-extract) methods\n* make small changes to your Python files (change parameters, add notes, etc)\n\nThe first half of the **TF** module holds the functions. You can use these as functions within your own Python code. The functions are documented at the bottom of this README.\n\nThe second half of the module's code contains the simple command shell. [If you don't need the shell, just delete everything from `-----cut here` downward.]\n\n\n## Simple Command Line\n\nBy invoking `tf.main()`, you will be presented a command prompt, similar to Linux, where the prompt shows you what directory/folder you are currently in, and a '$'. \n\nFrom there, you can enter one of these commands:\n\n```\ncp    \u003csrc-file\u003e \u003cdest-file\u003e  \nmv    \u003csrc-file\u003e \u003cdest-file\u003e\nrm    \u003cfilename\u003e\n\ndir   [\u003cdir name\u003e]\ncd    [\u003cdest dir\u003e]\nmkdir \u003cdirname\u003e\nrmdir \u003cdirname\u003e\n\ncat   [-n] [-l\u003cn\u003e-\u003cm\u003e] \u003cfilename\u003e\ngrep  \u003cpattern\u003e \u003cfilename\u003e\nsed   \u003cpattern\u003e \u003cfilename\u003e\n\nhelp\n```\n\nYou can use synonyms for these: `copy = cp`, `move = rename = mv`, `del = rm`, `list = cat`, `ls = dir`. The `mv/move/rename` can rename directories. \n\nFor the `cat/list` command, you can enable line numbers with `-n` and you can limit the display range with `-l n-m` where `n` and `m` are decimal numbers (and n should be less than m). These are all valid uses of `cat`\n\n```\ncat -n log.txt             # whole file\ncat -n -l223 log.txt       # one line  \ncat -l 223-239 log.txt     # 17 lines\ncat -l244-$ log.txt        # from 244 to the end\n```\n\nFor `grep`  and `sed`, the patterns are *MicroPython* regular explressions, from the `re` module. If a pattern has a space character in it, then the pattern **must** be wrapped in  single-quote ' characters; patterns without an embedded space char can simply be typed. [The line parser is basically a `str.split()` unless a leading ' is detected.] To include a single quote in a quoted-pattern, you can escape it with ``\\'` .\n\nThe documentation for the `sed` command is [here](#sed)\n\nHere are some valid uses of `sed` and `grep`\n\n```text\ngrep #define main.c\ngrep '^\\s*#define\\s+[A-Z]' main.c\nsed 1,100s/recieve/receive/g doc.txt\nsed '33-$s/it is/it\\'s/g' doc.txt\nsed '45i   a new line of indented text' doc.txt\n```\n\nThe **REPL** typing-history is functional, so you can use the up-arrow to recall the last 4-5 commands. Use the left-arrow and backspace to correct lines that have errors.\n\nCommands with invalid syntax return a line of information, and are ignored. Non valid commands are simply eaten and ignored.\n\n### Limitations\n\nIn its present form, the module has these limitations:  \n\n* filenames are limited to 255 chars\n* file contents must be text\n\t* or have a `\\n` at least every 4096 characters\n\t* `sed()` requires lines \u003c=2048 characters, and this `sed()` will not match binary chars\n* in the simple shell\n  * filenames must not have spaces\n  * patterns with spaces ***must*** be quoted\n  * the target of `cp` and `mv` *cannot* be a simple a directory-name as in Linux; write the whole filename *w.r.t* the current directory\n* for the `sed` function and command, the [search](https://docs.micropython.org/en/latest/library/ure.html) pattern can have wildcards like ``\\s`, `\\w` and `\\d`. The replace pattern cannot have *any* of these, and can only have `\\0`, `\\1`, etc\n  * search patterns involving \\ escapes other than those and `\\'` probably won't work\n* the complexity of pattern matching is limited. \n  * try to format the grep patterns so they avoid deep stack recursion. For example, `([^#]|\\\\#)\\s*` has a very generous search term as the first half, and can cause deep-stack recursion. The equivalent `(\\\\#|[^#])\\s*` is more likely to succeed.\n* with `sed`, lines are parsed and saved one-line-at-a-time, so pattern matching to `\\n` and `\\r` does not work; `sed` cannot work over line boundaries\n* this simple shell is different than [`mpfshell`](https://github.com/wendlers/mpfshell) in that *this* shell runs entirely on the target device. There is no allowance in this shell for transferring files in/out of the target.\n* after a restart of your *MicroPython* board, you can invoke the shell with `import tf`; if you `^C` out of the shell, the second invocation of `tf` will have to be `import tf` followed by `tf.main()`, since the python interpreter caches the module and only loads it once per restart; you can intentionally restart the REPL prompt by hitting `^D` \n \n### Examples\n\nMake a simple change to a source file, perhaps modify a constant.\n\n```\n[command line]  \n   /$ grep CITY main.py\n   58 CITY_NAME = 'Toronto'\n   /$ sed '58s/CITY_NAME = \\'Toronto\\'/CITY_NAME = \\'Ottawa\\'/' main.py  \n   /$ sed 58s/Toronto/Ottawa/ main.py\n[python function]  \n   tf.sed('main.py','10-30s/CITY_NAME = \\'Toronto\\'/CITY_NAME     = \\'Ottawa\\'/')  \n```\n\nRemove some comments from a source file.\n\n```\n[command line]\n   /$ sed X/^#\\s*TODO:/ main.py\n[python function]\n   tf.sed('main.py','X/^#\\s*TODO:/')\n```\n\nSearch a log file for an incident\n\n```\n[command line]\n   /$ grep [Ee]rror log.txt\n   /$ grep '2021-02-12 16:\\d\\d' log.txt\n   \n   # search and keep a record\n   /$ cp log.txt log.details\n   /$ sed 'x/2021-02-12 16:\\d\\d` log.details\n\n[python function]\n   tf.grep('log.txt','^2021-02-12 16:\\d\\d',numbers=True)\n```\n\n## Installation\n\n~If you need help with getting connected to your *MicroPython* board, there are excellent howto guides here and here~ TODO! \n\nMove the 'tf.py' file over to the target. You can use `webrepl` [command line program](https://github.com/micropython/webrepl)  or the **WEBREPL** [web page](http://micropython.org/webrepl/) .  If you want the command line extensions, then send over the `tf_extend.py` file as well\n\nOnce the module is present in the file system of the target, you can use the **REPL** command line interface to invoke it\n\n```\n \u003e\u003e\u003e import tf\ntf module loaded; members cp(), cat(), _dir(), grep() and sed()\nsimple shell: cp/copy mv/move rm/del cat/list cd dir/ls mkdir rmdir grep sed help\n/$ \n```\n\nThis is the *simple command line*. You can type `dir` to get an idea of what's already in your flash file system, and `cat` to see the contents. [You'll probably find the files `boot.py` and `webrepl_cfg.py` are already installed]\n\n```\n  /$ dir\n -rwx all       230 boot.py\n -rwx all      2886 mail.log\n -rwx all      2401 main.py\n -rwx all      2259 main_test.py\n -rwx all     99182 mqtt.log\n -rwx all        98 test.py\n drwx all         2 test_dir\n -rwx all      6903 tf.py\n -rwx all        15 webrepl_cfg.py\n disk size:     392 KB   disk free: 212 KB\n /$ cd test_dir\n /test_dir$ dir\n -rwx all        98 test.py\n disk size:     392 KB   disk free: 212 KB\n /test_dir$ \n```\n\nIf you don't need the *simple command line*, you can still use the methods listed at the bototm of this readme. Feel free to cut the `tf.py` module in half by deleting everything below the line\n\n```\n  -----cut here\n```\n\n### Extensions\n\nI found the simple command line so useful, I added some extra non-file-related functions. These are included in the optional file `tf_extend.py`.  The available command list is extended to include\n\n```\nscan                      # scan and show the local AP's\nconnect essid password    # create a persistent wifi connection\nifconfig                  # show current ip address\nhost \u003cdomain.name\u003e        # do an DNS lookup\nfreq [160 | 80]           # get/set the ESP8266 frequency\nexec \u003cpython-filename\u003e    # execute a small python file\nfree                      # display the heap size: used + free\nwc \u003cfilename\u003e             # display the line count, word count and bytes\nless/more [-n] \u003cfilename\u003e # similar to cat, but displays 30 lines at a time\nbtree \u003cfilename\u003e          # display the content of a BTREE database\n```\nSynonyms: `ip = ifconfig`, `more = less`, `dig = nslookup = host`\n\nThe `tf.py` module checks to see if the `tf_extend.py` files exists, and forwards unknown commands to it. The `help` system also extends when the extension file exists.\n\nInstalling the extensions module uses about 3k of flash/disk space and 4kB of heap ram.\n\n## Performance\n\nTypical performance on an ESP8266 @80MHz, 90kB log file, 1200 lines; serial connected terminal @115200baud\n\n| operation            | time     | bytes/sec      |\n| --------------------:| --------:| --------------:|\n| copy                 | 5.7 s    | 16kB/s         |\n| cat                  | 8.3 s    | 10.8kB/s       |\n| grep                 | 7.5s     | 12kB/s         |\n| sed-append           | 6.4s     | 14KB/s         |\n| sed-search/replace   | 8.0-8.2s | 11.0-11.25kB/s |\n| sed-extract 30 lines | 2.5s     | 36kB/s         |\n\n**Note**: The copy() time is indicative of the flash-write speed. The grep() and cat() speeds are indicative of the serial rate, as all the characters must be sent through the UART at 115kbaud=11.5kB/s. The sed-extract() is faster, because it only writes 30 lines of text to the flash. The sed-append() is constrained by having to write the entire file.\n\n\n\n## Functions\n\nIf you don't need the command line, you're welcome to just use the functions provided by the **tf** module. You would typically invoke the as members of tf: \n\n```\nimport tf\ntry:\n  tf.cp(\"log.txt\",\"log.bak\")\nexcept:\n  print(\"problem copying file\")\n```\n\n### cp()\n\n```\n   cp(src-filename, dest-filename)\n   in: src-filename    file to read\n       dest-filename   file to write\n   returns: Null\n   except: OSError if src or dest file cannot be found/created\n```\n\nSimply copies a source file to a destination file. Filenames may include folders or . or .. prefixes; use `/` to separate folder+filename. The destination is overwritten if it exists. This function reads-\u0026-writes one line at a time, so it can handle megabyte files. Typical speeds are 100kB/sec on an ESP8266. \n\n**NOTE** this function *only works on text files* delimited by `\\n`. Line lengths of up to 4096 work fine on the ESP8266.\n\n### cat()\n\n```\n    cat(filename, first=1, last=1000000, numbers=False, title=True)\n    in: filename    file to read and display\n        first       the first line to display\n        last        the last line to display\n        numbers     whether to prepend each line with line-number + space\n        title       whether to prepend the listing with the filename\n    return: Null\n    except: OSError if file cannot be found\n```\n\nDisplays the source file on the screen.  You can specify a line range, and whether line numbers are displayed, and whether to put a *title line* on the output display.  \n\n### _dir()\n\n```\n    dir(directory-name='.')\n    in:     directory-name     defaults to current directory\n    return: Null\n    except: OSError if directory doesn't exist\n```\n\nDisplays the contents of the current working directory. Files and folders are marked; ownership is assumed to be `all` and all are assumed to be `rwx` (read+write+execute). The file size is also shown and the disk size summary is shown at the bottom. \n\nFile dates are not displayed, as they all depend on the time from last reboot, and don't mean much in this environment.\n\nNOTE: the name is `_dir()` because `dir()` is a python builtin.\n\n### grep()\n\n```\n    grep(filename, pattern, numbers=False)\n    in:  filename         the file to scan\n         pattern          a python regex to match\n         numbers          whether to prepend a line-number + space \n    return: Null\n    except: ValueError if the pattern fails to compile as reg-ex\n        OSError if the file cannot be found\n        RunTimeError if the reg-ex parsing uses up all the memory\n```\n\nYou can search a file for a pattern, and any matching lines are displayed. Searches are restricted to within a line, don't bother with `\\r` and `\\n` searches. \n\n \n#### Examples\n\n```\ntf.grep('log.txt', '2021-03-\\d\\d')\ntf.grep('config.txt', '^user\\s*=')\ntf.grep('config.ini', '\\[\\w*\\]', numbers = True)\n```\n\n### sed()\n\n```\n  sed(filename, pattern, bak_ext=\".bak\")\n  in:  filename       the file to edit\n       pattern        a sed pattern, involving one of \"aidsxX\"\n       bak_ext        the extension to use when creating the file backup (with the dot)\n  return: tuple(number of lines in the input file, number of lines modified/added/deleted/matched)\n  except: OSError     the file cannot be found, or the backup cannot be created\n     ValueError       the reg-ex pattern fails to compile\n     RunTimeError     the reg-ex parsing uses up all the memory\n```\n\nThe *sed()* function is an inline file editor, based on `sed` from the Unix world. When invoked, it first renames the source file to have a `.bak` extension. That file is opened and each line of the source file is loaded in, and a regex pattern match is performed. If the line is changed/found/inserted, then the output is streamed to the new (output) file with the same name as the original; it appears to the user that the files is edited-in-place, with a .bak file created. \n\nThis version of `sed` has 6 commands:\n\n* a appends a line\n* i inserts a line\n* d deletes a line or lines\n* s does a search and replace\n* x does a grep and only saves lines that match\n* X does a grep and only saves lines that do not match\n\nIf the single-letter command is preceded by a number or number-range, then the edit operation only applies to that line(s). A number range may be separated by `-` hyphen or `,` comma. Use `$` to indicate end-of-file.\n\n#### Examples\n\n```\n12aMAX_FILE_NAME=255             insert a line AFTER line 12\n12iDEFAULT_DIR = \"/\"             insert a line BEFORE line 12\n43-45d                           delete lines 43, 44 and 45\n1,20s/^#\\s*/##  /                only in lines 1 through 20, replace lines that \n                                 start with a # followed by whitespace\n                                 with two-# and two-spaces....to align some comments\n```\n\nThe `i/a/d` commands should be preceeded by a line number, or range; `sed()` will *insert*, *append* or *delete* once for each line in the range. \n \nThe `x/X` patterns are wrapped in a pair of delimiter characters, typically `/`, although almost any other character is allowed other than space or one of `\\^$()[]`. Valid X commands are:\n\n```\nx/abcd/\n10-20X/\\w*\\s*\\d\\d/\nx!ratio x/y!\n```\n\nSimilarly, the `s` patterns are wrapped in a triplet of delimiter characters, typcially `/` also. If the search pattern has `()` groups, the replace pattern can refer to them with `\\1 \\2`,etc. The /search/replace/ pattern may have a  `g` suffix, to replace replaces multiple occurrences on a line. Valid 's' commands are\n\n```\ns/toronto/Toronto/\ns/thier/their/g\n120-$s/while\\s*(True|False)/while 1/\ns@ratio\\s*=\\s*num/denom@ratio = num/denom if denom else 0@\n```\n\n**Note**: The function version of sed() can have embedded space characters in the pattern; the command line version (above) requires single-quotes around patterns that have space characters.\n\n**Note**: You will need some free space on your disk, the same size as the source file, as a backup file is *always* made. To edit an 800k file, you should have 800k of free space.\n\n**Note**: `sed()` errors may leave the subject-file empty, but it almost always make the backup file before failing.\n\n### General Notes\n\n**Note**: On error, all the functions above throw exceptions. The simple command line shell above catches the exceptions. If you use the functions, wrap them up in `try/except`.\n\n**Note**: The functions for\n\n* file delete (`rm, del`)\n* file move (`mv, move, rename`)\n* change/make/delete directory/folder (`chdir, mkdir, rmdir`)\n\nare not included in this list, because the `os` module already has functions that implement these directly: `os.remove(), os.rename(), os.chdir(), os.mkdir(), os.rmdir()`\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpatbeirne%2Ftf","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpatbeirne%2Ftf","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpatbeirne%2Ftf/lists"}