Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
14230ccb26 | ||
|
|
6e063af4fd | ||
|
|
9a6fdcdba0 | ||
|
|
1d21f76d11 | ||
|
|
baffd3bf31 | ||
|
|
7c246a73dc | ||
|
|
833e32f146 | ||
|
|
2ebc9e3d2e | ||
|
|
3d79460bb6 | ||
|
|
2459d68bcb | ||
|
|
79adae017f | ||
|
|
b30f1b5bb9 | ||
|
|
8abff6f998 | ||
|
|
0467aacef3 | ||
|
|
eb68b76c8a | ||
|
|
ddbea490ea | ||
|
|
83857b5571 | ||
|
|
34f88c5948 | ||
|
|
bbfa19cac2 | ||
|
|
ba44d1ec23 | ||
|
|
ef4114d1fb | ||
|
|
d43a8d3e49 | ||
|
|
e1c57a284e |
@@ -1,39 +0,0 @@
|
||||
Creative Commons CC0 1.0 Universal
|
||||
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER.
|
||||
Statement of Purpose
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work").
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
|
||||
|
||||
For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
|
||||
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following:
|
||||
|
||||
i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
|
||||
|
||||
ii. moral rights retained by the original author(s) and/or performer(s);
|
||||
|
||||
iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work;
|
||||
|
||||
iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below;
|
||||
|
||||
v. rights protecting the extraction, dissemination, use and reuse of data in a Work;
|
||||
|
||||
vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
|
||||
|
||||
vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
|
||||
|
||||
2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose.
|
||||
|
||||
4. Limitations and Disclaimers.
|
||||
|
||||
a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
|
||||
|
||||
b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
|
||||
|
||||
c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
|
||||
|
||||
d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work.
|
||||
@@ -1,3 +1,411 @@
|
||||
# tf
|
||||
# TF
|
||||
|
||||
TF is a small command line for a MicroPython target.
|
||||
A module for manipulating **T**ext **F**iles in the *MicroPython* environment.
|
||||
|
||||
[TOC]
|
||||
|
||||
#### TL;DR
|
||||
A small app for the *MicroPython* board environment, to allow easy access to text files stored in the local flash file system.
|
||||
|
||||
*Tested on 1.21 (Oct/23) and everything works properly*
|
||||
|
||||
## Oveview
|
||||
|
||||
I 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.
|
||||
|
||||
This **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.
|
||||
|
||||
For example, to make a backup of a file from your Python app, you can call
|
||||
|
||||
```
|
||||
tf.cp('log.txt','log.2021-03-20.bak')
|
||||
```
|
||||
|
||||
or you can use the builtin command line and
|
||||
|
||||
```
|
||||
/$ cp mail.log m.log.bak
|
||||
/$ dir
|
||||
-rwx all 230 boot.py
|
||||
-rwx all 2886 m.log.bak
|
||||
-rwx all 2886 mail.log
|
||||
-rwx all 2401 main.py
|
||||
-rwx all 2259 main_test.py
|
||||
-rwx all 99182 mqtt.log
|
||||
-rwx all 6949 tf.py
|
||||
-rwx all 15 webrepl_cfg.py
|
||||
disk size: 392 KB disk free: 196 KB
|
||||
|
||||
/$ cat -n -l 1000-1005 mqtt.log
|
||||
====mqtt.log=====
|
||||
1000 1616120701: Client mosq-d911rjWHX3Rdwcntoo disconnected.
|
||||
1001 1616124181: New connection from 72.53.209.21 on port 1883.
|
||||
1002 1616124181: New client connected from 72.53.209.21 as mosq-kwcmiGmZ7jlEVRecrU (c1, k60).
|
||||
1003 1616124181: Client mosq-kwcmiGmZ7jlEVRecrU disconnected.
|
||||
1004 1616126374: Socket error on client DVES_98843E, disconnecting.
|
||||
1005 1616126425: Client DVES_83244E has exceeded timeout, disconnecting.
|
||||
|
||||
/$ grep 24.114.80.\d+ mqtt.log
|
||||
977 1616120273: New connection from 24.114.80.91 on port 1883.
|
||||
980 1616120273: New client connected from 24.114.80.91 as Rutherford1616120233590 (c1, k60, u'patb').
|
||||
1046 1616142039: New connection from 24.114.80.109 on port 1883.
|
||||
1049 1616142039: New client connected from 24.114.80.109 as Rutherford1616120233590 (c1, k60, u'patb').
|
||||
|
||||
/$
|
||||
```
|
||||
Uses:
|
||||
|
||||
* make a backup copy of a file
|
||||
* examine and clean up your filesystem and its directories
|
||||
* scan a mega-byte log file for entries using the `grep`(search) or `sed` (search-and-extract) methods
|
||||
* make small changes to your Python files (change parameters, add notes, etc)
|
||||
|
||||
The 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.
|
||||
|
||||
The 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.]
|
||||
|
||||
|
||||
## Simple Command Line
|
||||
|
||||
By 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 '$'.
|
||||
|
||||
From there, you can enter one of these commands:
|
||||
|
||||
```
|
||||
cp <src-file> <dest-file>
|
||||
mv <src-file> <dest-file>
|
||||
rm <filename>
|
||||
|
||||
dir [<dir name>]
|
||||
cd [<dest dir>]
|
||||
mkdir <dirname>
|
||||
rmdir <dirname>
|
||||
|
||||
cat [-n] [-l<n>-<m>] <filename>
|
||||
grep <pattern> <filename>
|
||||
sed <pattern> <filename>
|
||||
|
||||
help
|
||||
```
|
||||
|
||||
You can use synonyms for these: `copy = cp`, `move = rename = mv`, `del = rm`, `list = cat`, `ls = dir`. The `mv/move/rename` can rename directories.
|
||||
|
||||
For 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`
|
||||
|
||||
```
|
||||
cat -n log.txt # whole file
|
||||
cat -n -l223 log.txt # one line
|
||||
cat -l 223-239 log.txt # 17 lines
|
||||
cat -l244-$ log.txt # from 244 to the end
|
||||
```
|
||||
|
||||
For `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 ``\'` .
|
||||
|
||||
The documentation for the `sed` command is [here](#sed)
|
||||
|
||||
Here are some valid uses of `sed` and `grep`
|
||||
|
||||
```text
|
||||
grep #define main.c
|
||||
grep '^\s*#define\s+[A-Z]' main.c
|
||||
sed 1,100s/recieve/receive/g doc.txt
|
||||
sed '33-$s/it is/it\'s/g' doc.txt
|
||||
sed '45i a new line of indented text' doc.txt
|
||||
```
|
||||
|
||||
The **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.
|
||||
|
||||
Commands with invalid syntax return a line of information, and are ignored. Non valid commands are simply eaten and ignored.
|
||||
|
||||
### Limitations
|
||||
|
||||
In its present form, the module has these limitations:
|
||||
|
||||
* filenames are limited to 255 chars
|
||||
* file contents must be text
|
||||
* or have a `\n` at least every 4096 characters
|
||||
* `sed()` requires lines <=2048 characters, and this `sed()` will not match binary chars
|
||||
* in the simple shell
|
||||
* filenames must not have spaces
|
||||
* patterns with spaces ***must*** be quoted
|
||||
* 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
|
||||
* 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
|
||||
* search patterns involving \ escapes other than those and `\'` probably won't work
|
||||
* the complexity of pattern matching is limited.
|
||||
* 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.
|
||||
* 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
|
||||
* 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.
|
||||
* 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`
|
||||
|
||||
### Examples
|
||||
|
||||
Make a simple change to a source file, perhaps modify a constant.
|
||||
|
||||
```
|
||||
[command line]
|
||||
/$ grep CITY main.py
|
||||
58 CITY_NAME = 'Toronto'
|
||||
/$ sed '58s/CITY_NAME = \'Toronto\'/CITY_NAME = \'Ottawa\'/' main.py
|
||||
/$ sed 58s/Toronto/Ottawa/ main.py
|
||||
[python function]
|
||||
tf.sed('main.py','10-30s/CITY_NAME = \'Toronto\'/CITY_NAME = \'Ottawa\'/')
|
||||
```
|
||||
|
||||
Remove some comments from a source file.
|
||||
|
||||
```
|
||||
[command line]
|
||||
/$ sed X/^#\s*TODO:/ main.py
|
||||
[python function]
|
||||
tf.sed('main.py','X/^#\s*TODO:/')
|
||||
```
|
||||
|
||||
Search a log file for an incident
|
||||
|
||||
```
|
||||
[command line]
|
||||
/$ grep [Ee]rror log.txt
|
||||
/$ grep '2021-02-12 16:\d\d' log.txt
|
||||
|
||||
# search and keep a record
|
||||
/$ cp log.txt log.details
|
||||
/$ sed 'x/2021-02-12 16:\d\d` log.details
|
||||
|
||||
[python function]
|
||||
tf.grep('log.txt','^2021-02-12 16:\d\d',numbers=True)
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
~If you need help with getting connected to your *MicroPython* board, there are excellent howto guides here and here~ TODO!
|
||||
|
||||
Move 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
|
||||
|
||||
Once the module is present in the file system of the target, you can use the **REPL** command line interface to invoke it
|
||||
|
||||
```
|
||||
>>> import tf
|
||||
tf module loaded; members cp(), cat(), _dir(), grep() and sed()
|
||||
simple shell: cp/copy mv/move rm/del cat/list cd dir/ls mkdir rmdir grep sed help
|
||||
/$
|
||||
```
|
||||
|
||||
This 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]
|
||||
|
||||
```
|
||||
/$ dir
|
||||
-rwx all 230 boot.py
|
||||
-rwx all 2886 mail.log
|
||||
-rwx all 2401 main.py
|
||||
-rwx all 2259 main_test.py
|
||||
-rwx all 99182 mqtt.log
|
||||
-rwx all 98 test.py
|
||||
drwx all 2 test_dir
|
||||
-rwx all 6903 tf.py
|
||||
-rwx all 15 webrepl_cfg.py
|
||||
disk size: 392 KB disk free: 212 KB
|
||||
/$ cd test_dir
|
||||
/test_dir$ dir
|
||||
-rwx all 98 test.py
|
||||
disk size: 392 KB disk free: 212 KB
|
||||
/test_dir$
|
||||
```
|
||||
|
||||
If 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
|
||||
|
||||
```
|
||||
-----cut here
|
||||
```
|
||||
|
||||
### Extensions
|
||||
|
||||
I 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
|
||||
|
||||
```
|
||||
scan # scan and show the local AP's
|
||||
connect essid password # create a persistent wifi connection
|
||||
ifconfig # show current ip address
|
||||
host <domain.name> # do an DNS lookup
|
||||
freq [160 | 80] # get/set the ESP8266 frequency
|
||||
exec <python-filename> # execute a small python file
|
||||
free # display the heap size: used + free
|
||||
wc <filename> # display the line count, word count and bytes
|
||||
less/more [-n] <filename> # similar to cat, but displays 30 lines at a time
|
||||
btree <filename> # display the content of a BTREE database
|
||||
```
|
||||
Synonyms: `ip = ifconfig`, `more = less`, `dig = nslookup = host`
|
||||
|
||||
The `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.
|
||||
|
||||
Installing the extensions module uses about 3k of flash/disk space and 4kB of heap ram.
|
||||
|
||||
## Performance
|
||||
|
||||
Typical performance on an ESP8266 @80MHz, 90kB log file, 1200 lines; serial connected terminal @115200baud
|
||||
|
||||
| operation | time | bytes/sec |
|
||||
| --------------------:| --------:| --------------:|
|
||||
| copy | 5.7 s | 16kB/s |
|
||||
| cat | 8.3 s | 10.8kB/s |
|
||||
| grep | 7.5s | 12kB/s |
|
||||
| sed-append | 6.4s | 14KB/s |
|
||||
| sed-search/replace | 8.0-8.2s | 11.0-11.25kB/s |
|
||||
| sed-extract 30 lines | 2.5s | 36kB/s |
|
||||
|
||||
**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.
|
||||
|
||||
|
||||
|
||||
## Functions
|
||||
|
||||
If 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:
|
||||
|
||||
```
|
||||
import tf
|
||||
try:
|
||||
tf.cp("log.txt","log.bak")
|
||||
except:
|
||||
print("problem copying file")
|
||||
```
|
||||
|
||||
### cp()
|
||||
|
||||
```
|
||||
cp(src-filename, dest-filename)
|
||||
in: src-filename file to read
|
||||
dest-filename file to write
|
||||
returns: Null
|
||||
except: OSError if src or dest file cannot be found/created
|
||||
```
|
||||
|
||||
Simply 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-&-writes one line at a time, so it can handle megabyte files. Typical speeds are 100kB/sec on an ESP8266.
|
||||
|
||||
**NOTE** this function *only works on text files* delimited by `\n`. Line lengths of up to 4096 work fine on the ESP8266.
|
||||
|
||||
### cat()
|
||||
|
||||
```
|
||||
cat(filename, first=1, last=1000000, numbers=False, title=True)
|
||||
in: filename file to read and display
|
||||
first the first line to display
|
||||
last the last line to display
|
||||
numbers whether to prepend each line with line-number + space
|
||||
title whether to prepend the listing with the filename
|
||||
return: Null
|
||||
except: OSError if file cannot be found
|
||||
```
|
||||
|
||||
Displays 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.
|
||||
|
||||
### _dir()
|
||||
|
||||
```
|
||||
dir(directory-name='.')
|
||||
in: directory-name defaults to current directory
|
||||
return: Null
|
||||
except: OSError if directory doesn't exist
|
||||
```
|
||||
|
||||
Displays 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.
|
||||
|
||||
File dates are not displayed, as they all depend on the time from last reboot, and don't mean much in this environment.
|
||||
|
||||
NOTE: the name is `_dir()` because `dir()` is a python builtin.
|
||||
|
||||
### grep()
|
||||
|
||||
```
|
||||
grep(filename, pattern, numbers=False)
|
||||
in: filename the file to scan
|
||||
pattern a python regex to match
|
||||
numbers whether to prepend a line-number + space
|
||||
return: Null
|
||||
except: ValueError if the pattern fails to compile as reg-ex
|
||||
OSError if the file cannot be found
|
||||
RunTimeError if the reg-ex parsing uses up all the memory
|
||||
```
|
||||
|
||||
You 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.
|
||||
|
||||
|
||||
#### Examples
|
||||
|
||||
```
|
||||
tf.grep('log.txt', '2021-03-\d\d')
|
||||
tf.grep('config.txt', '^user\s*=')
|
||||
tf.grep('config.ini', '\[\w*\]', numbers = True)
|
||||
```
|
||||
|
||||
### sed()
|
||||
|
||||
```
|
||||
sed(filename, pattern, bak_ext=".bak")
|
||||
in: filename the file to edit
|
||||
pattern a sed pattern, involving one of "aidsxX"
|
||||
bak_ext the extension to use when creating the file backup (with the dot)
|
||||
return: tuple(number of lines in the input file, number of lines modified/added/deleted/matched)
|
||||
except: OSError the file cannot be found, or the backup cannot be created
|
||||
ValueError the reg-ex pattern fails to compile
|
||||
RunTimeError the reg-ex parsing uses up all the memory
|
||||
```
|
||||
|
||||
The *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.
|
||||
|
||||
This version of `sed` has 6 commands:
|
||||
|
||||
* a appends a line
|
||||
* i inserts a line
|
||||
* d deletes a line or lines
|
||||
* s does a search and replace
|
||||
* x does a grep and only saves lines that match
|
||||
* X does a grep and only saves lines that do not match
|
||||
|
||||
If 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.
|
||||
|
||||
#### Examples
|
||||
|
||||
```
|
||||
12aMAX_FILE_NAME=255 insert a line AFTER line 12
|
||||
12iDEFAULT_DIR = "/" insert a line BEFORE line 12
|
||||
43-45d delete lines 43, 44 and 45
|
||||
1,20s/^#\s*/## / only in lines 1 through 20, replace lines that
|
||||
start with a # followed by whitespace
|
||||
with two-# and two-spaces....to align some comments
|
||||
```
|
||||
|
||||
The `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.
|
||||
|
||||
The `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:
|
||||
|
||||
```
|
||||
x/abcd/
|
||||
10-20X/\w*\s*\d\d/
|
||||
x!ratio x/y!
|
||||
```
|
||||
|
||||
Similarly, 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
|
||||
|
||||
```
|
||||
s/toronto/Toronto/
|
||||
s/thier/their/g
|
||||
120-$s/while\s*(True|False)/while 1/
|
||||
s@ratio\s*=\s*num/denom@ratio = num/denom if denom else 0@
|
||||
```
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
**Note**: `sed()` errors may leave the subject-file empty, but it almost always make the backup file before failing.
|
||||
|
||||
### General Notes
|
||||
|
||||
**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`.
|
||||
|
||||
**Note**: The functions for
|
||||
|
||||
* file delete (`rm, del`)
|
||||
* file move (`mv, move, rename`)
|
||||
* change/make/delete directory/folder (`chdir, mkdir, rmdir`)
|
||||
|
||||
are 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()`
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
# tf Text File manipulations
|
||||
# for micropython and other tiny environments
|
||||
# (c) Pat Beirne patb@pbeirne.com
|
||||
import re,os,sys,gc
|
||||
|
||||
# ====legend====
|
||||
# e=end
|
||||
# f=input file
|
||||
# g=output file
|
||||
# i=iteration variable
|
||||
# m=line range
|
||||
# r=replace text
|
||||
# s=start/search/string
|
||||
# sp=search regex
|
||||
|
||||
def transfer(src,dest,first=1,last=0xFFFFFFFF,numbers=False,grep_func=None):
|
||||
#src is a filename, dst is a handle
|
||||
i=0
|
||||
with open(src) as f:
|
||||
for lin in f:
|
||||
i=i+1
|
||||
if i<first or i>last:
|
||||
continue
|
||||
if grep_func and not grep_func(lin):
|
||||
continue
|
||||
if numbers:
|
||||
dest.write(str(i)+' ')
|
||||
dest.write(lin)
|
||||
|
||||
def cp(src,dest):
|
||||
with open(dest,'w') as g:
|
||||
transfer(src,g)
|
||||
|
||||
def cat(filename, first=1, last=1000000, numbers=False, title=True):
|
||||
if title:
|
||||
print("===={}====".format(filename))
|
||||
transfer(filename,sys.stdout,first,last,numbers=numbers)
|
||||
|
||||
def grep(filename, pattern, numbers=False):
|
||||
m=re.compile(pattern)
|
||||
transfer(filename,sys.stdout,numbers=numbers,grep_func=(lambda x:m.search(x[:-1])))
|
||||
|
||||
def sed(filename, sed_cmd, bak_ext=".bak"):
|
||||
# parse the sed_cmd
|
||||
# group 1,3 are the n-start, n-end group 4 is command: aidsxX
|
||||
a=re.search("^(\d*)([,-](\d+|\$))?\s*([sdaixX])(.*)",sed_cmd)
|
||||
if not a:
|
||||
raise ValueError("sed() failed; pattern must be a number-range followed by one of sdaixX; no changes applied")
|
||||
op,args=a.group(4),a.group(5)
|
||||
|
||||
s,e=1,1000000
|
||||
if a.group(1):
|
||||
s=e=int(a.group(1))
|
||||
if a.group(3):
|
||||
e=1000000 if a.group(3)=='$' else int(a.group(3))
|
||||
|
||||
if op in "aid" and e-s==1000000:
|
||||
raise ValueError("sed(a/i/d) should have a line number")
|
||||
#print("sed command parser of <{}> returned {} {} {}".format(op, cmd, a.group(1), a.group(3)))
|
||||
if op in "sxX":
|
||||
if len(args)<2 or args[0] in "\^$()[]":
|
||||
raise ValueError("invalid sed argument: "+op+args)
|
||||
dl=args[0]
|
||||
if op=='s':
|
||||
gs=re.search(dl+"([^"+dl+"]*)"+dl+"([^"+dl+"]*)"+dl+"(g)?",args)
|
||||
else:
|
||||
gs=re.search(dl+"([^"+dl+"]*)"+dl,args)
|
||||
if not gs:
|
||||
raise ValueError("invalid sed search pattern: "+op+args)
|
||||
ss=gs.group(1)
|
||||
if op=='s':
|
||||
r=gs.group(2)
|
||||
rm=0 if gs.group(3) else 1
|
||||
sp=re.compile(ss)
|
||||
|
||||
args=args + '\n'
|
||||
|
||||
try:
|
||||
os.rename(filename,filename+bak_ext)
|
||||
except:
|
||||
raise OSError("problem with filename",filename," backup failed; no changes made")
|
||||
|
||||
i=h=0
|
||||
with open(filename+bak_ext) as f:
|
||||
with open(filename,'w') as g:
|
||||
for lin in f:
|
||||
i=i+1
|
||||
m=(s <= i <= e)
|
||||
if op=='s' and m:
|
||||
lin=lin[:-1]
|
||||
if sp.search(lin): h+=1
|
||||
lin=sp.sub(r,lin,rm)+'\n'
|
||||
if op=='d' and m:
|
||||
h+=1
|
||||
continue # delete line
|
||||
if op=='i' and m:
|
||||
#print("insert a line before {} <{}>".format(i,extra))
|
||||
g.write(args)
|
||||
h+=1
|
||||
if op in "aids":
|
||||
g.write(lin)
|
||||
elif m and (op=='x' if sp.search(lin) else op=='X'):
|
||||
g.write(lin)
|
||||
h+=1
|
||||
if op=='a' and m:
|
||||
#print("append a line after {} <{}>".format(i,extra))
|
||||
g.write(args)
|
||||
h+=1
|
||||
#f.write("--file modifed by sed()--\n")
|
||||
return (i, h)
|
||||
|
||||
def _dir(d='.'):
|
||||
for f in os.listdir(d):
|
||||
s=os.stat(d+'/'+f)
|
||||
print("{}rwx all {:9d} {}".format('d' if (s[0] & 0x4000) else '-',s[6],f ))
|
||||
s=os.statvfs('/')
|
||||
print("disk size:{:8d} KB disk free: {} KB".format(s[0]*s[2]//1024,s[0]*s[3]//1024))
|
||||
|
||||
'''-----cut here if you only need the functions-----'''
|
||||
def ext_cmd(a):
|
||||
return
|
||||
if 'tf_extend.py' in os.listdir():
|
||||
import tf_extend
|
||||
ext_cmd=tf_extend.cmd
|
||||
|
||||
def _help():
|
||||
print("==Simple shell v1.2 for Text Files")
|
||||
print(" cp/copy <src-file> <dest-file>")
|
||||
print(" mv/move/rename <src-file> <dest-file> \trm/del <file>")
|
||||
print(" cd [<folder>]\t\tmkdir <folder>\t\trmdir <folder>")
|
||||
print(" dir/ls [<folder>]")
|
||||
print(" cat/list [-n] [-l <n>,<m>] <file>")
|
||||
print(" grep <pattern> <file>")
|
||||
print(" sed <pattern> <file>")
|
||||
print(" pattern is <line-range><op><extra> eg: 's/search/replace/' 'x!TODO:!' '43,49d' '8itext'")
|
||||
print(" patterns with spaces require '-quotes\tsed ops are one of s/d/i/a/x/X")
|
||||
print(" sed cannot cross line boundaries\t\tsed s/x/X-patterns: non-/ delimiters are ok")
|
||||
print("file names must NOT have embedded spaces\toptions must be early on the command line")
|
||||
ext_cmd('help')
|
||||
|
||||
def parseQuotedArgs(st):
|
||||
#returns (pattern,file)
|
||||
st=st.strip()
|
||||
if st[0]=="'":
|
||||
p=re.search("'(.*?[^\\\\])'\s*(\S*)",st)
|
||||
if not p:
|
||||
print("error in quoted pattern:",st)
|
||||
return
|
||||
return p.group(1),p.group(2)
|
||||
else:
|
||||
return st.split(None,1)
|
||||
|
||||
def main():
|
||||
print("Simple shell: cp/copy mv/move rm/del cat/list cd dir/ls mkdir rmdir grep sed help")
|
||||
while 1:
|
||||
numbers=False
|
||||
r=input(os.getcwd()+"$ ")
|
||||
rp=r.split()
|
||||
if not len(rp): continue
|
||||
op=rp[0]
|
||||
if op in ('dir','ls'):
|
||||
try:
|
||||
_dir(rp[1] if len(rp)>1 else '.')
|
||||
except:
|
||||
print("directory not found")
|
||||
elif op in ('cat','list'):
|
||||
n=(" -n " in r) #print line-nums
|
||||
s,e=1,1000000 #start/end
|
||||
g=re.search("\s(-l\s*(\d+)([-,](\d+|\$)?)?)\s+",r[3:])
|
||||
if g:
|
||||
s=e=int(g.group(2))
|
||||
if g.group(3):
|
||||
e=int(g.group(4)) if g.group(4) and g.group(4).isdigit() else 1000000
|
||||
try:
|
||||
cat(rp[-1],s,e,numbers=n)
|
||||
except:
|
||||
print("file not found",rp[-1])
|
||||
elif op in('grep','sed'):
|
||||
if len(rp)<3:
|
||||
print(op,"pattern filename")
|
||||
continue
|
||||
p=parseQuotedArgs(r[4:])
|
||||
if not p:
|
||||
continue
|
||||
try:
|
||||
if op=='grep':
|
||||
grep(p[1],p[0],numbers=True)
|
||||
else:
|
||||
r=sed(p[1],p[0])
|
||||
if r:
|
||||
print("Lines processed: {} Lines modifed: {}".format(*r))
|
||||
except (ValueError, OSError) as e:
|
||||
print(e)
|
||||
except RuntimeError:
|
||||
print("problem with the regex; try a different pattern")
|
||||
elif op=='help':
|
||||
_help()
|
||||
ext_cmd(rp)
|
||||
elif ext_cmd(rp):
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
if op in ('cp','copy'):
|
||||
cp(rp[1],rp[2])
|
||||
elif op=='cd':
|
||||
os.chdir(rp[1] if len(rp)>1 else '/')
|
||||
elif op=='mkdir':
|
||||
os.mkdir(rp[1])
|
||||
elif op=='rmdir':
|
||||
os.rmdir(rp[1])
|
||||
elif op in('mv','move','rename'):
|
||||
os.rename(rp[1],rp[2])
|
||||
elif op in('rm','del'):
|
||||
os.remove(rp[1])
|
||||
else:
|
||||
print("command not implemented:",op)
|
||||
except IndexError:
|
||||
print("not enough argments; check syntax with 'help'")
|
||||
except OSError:
|
||||
print("file/folder not found or cannot be written")
|
||||
gc.collect()
|
||||
|
||||
if __name__=="tf":
|
||||
print("tf module loaded; members cp(), cat(), _dir(), grep() and sed()")
|
||||
main()
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
import os,sys,network,socket,time,machine,gc,tf,btree
|
||||
|
||||
# these helper classes let us use the tf.transfer() iterator,
|
||||
# by intercepting the .write()
|
||||
class wc():
|
||||
def __init__(self):
|
||||
self.c = [0,0,0] # lines, words & bytes
|
||||
def write(self,text):
|
||||
self.c[2] += len(text)
|
||||
self.c[0] += 1
|
||||
self.c[1] += len(text.split())
|
||||
|
||||
class lessor():
|
||||
def __init__(self,nums=False):
|
||||
self.i=0
|
||||
self.nums=nums
|
||||
def write(self,text):
|
||||
if self.i==-1: return
|
||||
self.i += 1
|
||||
if self.nums: sys.stdout.write(str(self.i)+' ')
|
||||
sys.stdout.write(text)
|
||||
if self.i%30==0:
|
||||
sys.stdout.write("====> press <enter> to see more, N or Q to quit <====\n")
|
||||
g=sys.stdin.read(1)
|
||||
if g=='\n': g=sys.stdin.read(1)
|
||||
if g in "nNqQ":
|
||||
self.i=-1
|
||||
|
||||
# the main entry point for the extension
|
||||
# returns True if the command was interpreted
|
||||
def cmd(args):
|
||||
cmd=args[0]
|
||||
if cmd in ('wc','more','less','exec') and len(args)<2:
|
||||
print("syntax: "+cmd+" <filename>")
|
||||
return True
|
||||
|
||||
if cmd in ('wc','more','less'):
|
||||
nums=False
|
||||
if cmd=='wc':
|
||||
w = wc()
|
||||
else:
|
||||
if args[1]=='-n':
|
||||
nums=True
|
||||
del(args[1])
|
||||
w = lessor(nums)
|
||||
try:
|
||||
tf.transfer(args[1],w)
|
||||
if cmd=='wc':
|
||||
print("lines: {}\twords: {}\tbytes: {}".format(*w.c))
|
||||
except:
|
||||
print("file not found: "+args[1])
|
||||
|
||||
elif cmd in ('ifconfig','ip'):
|
||||
ifc=network.WLAN().ifconfig()
|
||||
print("IP: {}\tmask: {}\tgateway: {}\tDNS: {}".format(*ifc))
|
||||
|
||||
elif cmd in ('host','nslookup','dig'):
|
||||
if len(args)<2:
|
||||
print("syntax: host <domain.name>")
|
||||
else:
|
||||
try:
|
||||
print("host <{}> is at {}".format(args[1],socket.getaddrinfo(args[1],80)[0][-1][0]))
|
||||
except:
|
||||
print("network/DNS not available")
|
||||
|
||||
elif cmd=='connect':
|
||||
if len(args)<3:
|
||||
print("syntax: connect <ssid> <password>")
|
||||
else:
|
||||
w=network.WLAN(network.STA_IF)
|
||||
w.connect(args[1],args[2])
|
||||
print("connecting...",end=' ')
|
||||
time.sleep(3)
|
||||
print(w.ifconfig() if w.isconnected() else "not yet connected; try 'ifconfig' in a few seconds")
|
||||
|
||||
elif cmd=='scan':
|
||||
w=network.WLAN(network.STA_IF)
|
||||
print("scanning...")
|
||||
s=w.scan()
|
||||
if len(s)==0:
|
||||
print("no AP found")
|
||||
return True
|
||||
for i in s:
|
||||
print("ch: {}\tRSSI: {}\t{}\tSSID: {}".format(i[2],i[3],"open" if i[4]==0 else "",i[0]))
|
||||
|
||||
elif cmd=='freq':
|
||||
# identify esp32 or esp8266
|
||||
try: # is this esp8266
|
||||
machine.TouchPad
|
||||
freqs=("160","80","240")
|
||||
except AttributeError:
|
||||
freqs=("160","80")
|
||||
if len(args)==1 or args[1] in freqs:
|
||||
if len(args)>1:
|
||||
machine.freq(int(args[1])*1000000)
|
||||
print("master cpu frequency {}MHz".format(machine.freq()//1000000))
|
||||
else:
|
||||
print("syntax: freq [ 160 | 80 | 240 ] ")
|
||||
|
||||
elif cmd=='btree':
|
||||
try:
|
||||
f=open(args[1])
|
||||
b=btree.open(f)
|
||||
print("Key\t\tValue")
|
||||
i=0
|
||||
for k,v in b.items():
|
||||
print("{:10}\t{}".format(k,v))
|
||||
i+=1
|
||||
if i%30==0:
|
||||
r=input("continue? ")
|
||||
if r=='n': break
|
||||
except OSError:
|
||||
print("file not found or is not a btree database")
|
||||
|
||||
elif cmd=='exec':
|
||||
try:
|
||||
exec(open(args[1]).read(),globals(),globals())
|
||||
except OSError:
|
||||
print("file not found")
|
||||
elif cmd=='free':
|
||||
print("memory used: {}\tmemory free:{}".format(gc.mem_alloc(),gc.mem_free()))
|
||||
elif cmd=='help':
|
||||
print("==Extended commands")
|
||||
print(" connect <essid> <password> \tscan")
|
||||
print(" ifconfig/ip \t\thost/dig/nslookup <domain.name>")
|
||||
print(" freq [160 | 80 | 240]\t\texec <python-filename>")
|
||||
print(" free \t\t\twc <filename>")
|
||||
print(" less/more [-n] <filename>")
|
||||
print(" btree <filename>")
|
||||
else: # command not found
|
||||
return False
|
||||
return True
|
||||
Executable
+56
@@ -0,0 +1,56 @@
|
||||
# tf_test Unit test for Text File manipulations
|
||||
import tf
|
||||
|
||||
# you should have a medium sized file called 'a' in '/'
|
||||
# and free space equivalent to 2x the size of 'a'
|
||||
|
||||
def bench():
|
||||
import time
|
||||
a=time.ticks_us()
|
||||
cp('a','b')
|
||||
b=time.ticks_us()
|
||||
print("time to copy={}".format((b-a)/1e6))
|
||||
input("next")
|
||||
|
||||
a=time.ticks_us()
|
||||
grep('a','kernel')
|
||||
b=time.ticks_us()
|
||||
print("time to grep={}".format((b-a)/1e6))
|
||||
input("next")
|
||||
|
||||
a=time.ticks_us()
|
||||
sed('a','s/kernel\s*/KERNEL /')
|
||||
b=time.ticks_us()
|
||||
print("time to sed-replace={}".format((b-a)/1e6))
|
||||
input("next")
|
||||
|
||||
os.remove('a.bak')
|
||||
a=time.ticks_us()
|
||||
cp('b','a')
|
||||
b=time.ticks_us()
|
||||
print("time to copy={}".format((b-a)/1e6))
|
||||
input("next")
|
||||
|
||||
a=time.ticks_us()
|
||||
sed('a','100-130x/(PM|AGP):/')
|
||||
b=time.ticks_us()
|
||||
print("time to sed-extract{}".format((b-a)/1e6))
|
||||
input("next")
|
||||
|
||||
a=time.ticks_us()
|
||||
cat('b', numbers=True)
|
||||
b=time.ticks_us()
|
||||
print("time to cat= {}".format((b-a)/1e6))
|
||||
input("next")
|
||||
|
||||
os.remove('a.bak')
|
||||
cp('b','a')
|
||||
|
||||
a=time.ticks_us()
|
||||
sed('a', '100a!! a line of text!!')
|
||||
b=time.ticks_us()
|
||||
print("time to sed-insert= {}".format((b-a)/1e6))
|
||||
|
||||
os.remove('a.bak')
|
||||
|
||||
|
||||
Reference in New Issue
Block a user