Last active
March 12, 2025 20:16
-
-
Save wolfmanjm/babf707a66b70de467ab9297b3b1ff80 to your computer and use it in GitHub Desktop.
swd2 frontend for line editing and history
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python -u | |
import subprocess | |
import selectors | |
import os | |
import time | |
import readline | |
import sys | |
import atexit | |
import threading | |
# set this to true to clear the line you just typed, as it is echoed by mecrisp anyway | |
clear_line = True | |
history_file = ".swdhistory" | |
process = None | |
def write2proc(line): | |
global process | |
process.stdin.write(f"{line}\n") | |
process.stdin.flush() | |
def sendchar(ch): | |
global process | |
process.stdin.write(ch) | |
process.stdin.flush() | |
def run(cmd): | |
global process | |
# stdout and stderr go straight to the terminal, but we pipe stdin so we can send commands | |
with subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=None, stderr=None, shell=False, universal_newlines=True, bufsize=0, encoding='utf-8', errors='replace') as p: | |
process = p | |
p.wait() | |
print('command complete') | |
# tab completion for forth words here | |
# we could add all known words, or just have a file with common words we want easy access to. | |
def completer(text, state): | |
# TODO read in a list of common forth words here | |
options = [word for word in ["words", "compiletoram", "dup", "swap"] if word.startswith(text)] | |
if state < len(options): | |
return options[state] | |
return None | |
def delete_last_line(): | |
# cursor up one line | |
sys.stdout.write('\x1b[1A') | |
# delete last line | |
sys.stdout.write('\x1b[2K') | |
def main(): | |
global process | |
try: | |
readline.read_history_file(history_file) | |
readline.set_history_length(1000) | |
except FileNotFoundError: | |
pass # No history file yet | |
readline.set_completer(completer) | |
readline.parse_and_bind("tab: complete") | |
t = threading.Thread(target=run, daemon=True, args=("swd2", )) | |
t.start() | |
print("SWD2 frontend with line editing and history. Type 'ctrl-D' to quit.") | |
while True: | |
try: | |
line = input() | |
if len(line) > 0 and clear_line: | |
delete_last_line() | |
write2proc(line) | |
except EOFError: | |
sendchar("\x04") | |
process.kill() | |
break # Handle Ctrl+D for exit | |
except KeyboardInterrupt: | |
sendchar("\x03") | |
print("Goodbye!") | |
t.join() | |
atexit.register(readline.write_history_file, history_file) | |
if __name__ == '__main__': | |
main() | |
''' | |
BSD 2-Clause License | |
Redistribution and use in source and binary forms, with or without | |
modification, are permitted provided that the following conditions are met: | |
1. Redistributions of source code must retain the above copyright notice, this | |
list of conditions and the following disclaimer. | |
2. Redistributions in binary form must reproduce the above copyright notice, | |
this list of conditions and the following disclaimer in the documentation | |
and/or other materials provided with the distribution. | |
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | |
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | |
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | |
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | |
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | |
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | |
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
''' | |
''' | |
This Python script provides a frontend for interacting with the `swd2` command-line tool. It incorporates features like line editing, command history, | |
and tab completion for specific Forth words. Here's a summary of the code: | |
1. **Imports**: The script imports several modules including `subprocess`, `selectors`, `os`, `time`, `readline`, `sys`, `atexit`, and `threading`. | |
2. **Global Variables**: | |
- `history_file`: Specifies the file to store command history. | |
- `process`: Holds a reference to the subprocess running `swd2`. | |
3. **Functions**: | |
- `write2proc(line)`: Sends a line of input to the `swd2` process's standard input and flushes it. | |
- `sendchar(ch)`: Sends a single character to the `swd2` process's standard input and flushes it. | |
- `run(cmd)`: Starts a subprocess with the given command, waits for it to complete, and prints 'command complete' when done. | |
- `completer(text, state)`: Provides tab completion for a list of predefined Forth words. | |
4. **Main Function**: | |
- Loads command history from `history_file` if it exists. | |
- Sets up the completer function for readline to provide tab completion. | |
- Starts the `swd2` process in a separate thread so that the main program can continue running and handle user input. | |
- Enters an infinite loop where it reads lines of input from the user, sends them to the `swd2` process, and handles `EOFError` (Ctrl+D) or | |
`KeyboardInterrupt` (Ctrl+C). | |
- Registers a function to save command history when the program exits. | |
5. **Exit Handling**: | |
- Uses `atexit.register` to ensure that the command history is written to `history_file` when the script terminates. | |
6. **Execution**: | |
- The `main()` function is called if the script is executed as the main module, starting the interaction with the `swd2` tool. | |
This script enhances the user experience by providing a more interactive and convenient way to use the `swd2` command-line tool through features like | |
command history and tab completion. | |
''' |
Significantly simplified the popen stuff, now works properly with control-C etc, and doesn't drop output. may need to run with python -u though to make sure nothing is buffered
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated to be better at catching all output