前言
Scheme 编程语言是一种Lisp方言,诞生于1975年,由 MIT 的 Gerald J. Sussman 和 Guy L. Steele Jr. 完成。它是现代两大Lisp方言之一;另一个方言是Common Lisp
历史悠久的Scheme依然活跃,拥有针对各种计算机平台和环境的实现,例如Racket、Guile、MIT Scheme、Chez Scheme等。
Tinyscheme是一款轻量级嵌入式的Scheme脚本解析器,使用R5RS(Revised 5 Report on the algorithmic language Scheme)语法规范,这个规范在1998年推出,现在已经被广泛使用。
虽然Tinyscheme没有说明文档,但是使用R5RS规范,因此具体的用法可以参考其他主流Scheme实现,比如Racket
Install
下载地址
1 https://sourceforge.net/projects/tinyscheme/files/tinyscheme/
1 2 3 4 $ make all $ ./scheme TinyScheme 1.41 ts>
文件目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 . ├── BUILDING ├── CHANGES ├── COPYING ├── dynload.c ├── dynload.h ├── hack.txt ├── init.scm ├── makefile ├── Manual.txt ├── MiniSCHEMETribute.txt ├── opdefines.h 定义了tinyscheme的保留关键字,开发者可以自定义新的功能。 ├── scheme.c 定义了如何解析代码 ├── scheme.h └── scheme-private.h
读文件
1 2 3 4 # 打开文件 (define shadow (open-input-file "/etc/shadow" )) # 读取文件一行并显示 (read shadow)
写文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 # 打开文件 (define ou (open-output-file "/tmp/shadow" )) # 定义要写的内容到变量 (define text "root:aaddd.asdasd.:13333:0:99999:3:::" ) # 打印变量 (display text) # 把变量值写到文件 (write text ou) # 把字符c写到文件 (write-char #\c ou) # 在ou末尾新增一行 (newline ou) # 保存并关闭文件 (close-output-port ou)
直接把字符串变量写到文件,会带双引号,因此使用字符逐个写入,一次写入大量字符可能会出现失败。另外如果是远程tinyscheme shell,单个换行字符\n不能被识别,因此使用\newline代替换行符。
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 import argparseif __name__ == '__main__' : try : parser = argparse.ArgumentParser( description="Write file by tinyscheme" ) parser.add_argument( "-l" , "--local-file" , help="directory to be read" , type=str, required=True ) parser.add_argument( "-t" , "--target-file" , help="directory to be write" , type=str, required=True ) args = parser.parse_args() file_path = args.local_file print("(define ou (open-output-file \"" + args.target_file + "\"))" ) try : with open(file_path, 'rb' ) as local_file: raw = local_file.read() for i in raw: if i == 10 : print("(newline ou)" ) else : print("(write-char #\\" , end="" ) if i == 13 : print("\r" , end="" ) elif i == 9 : print("\t" , end="" ) elif i == 32 : print(" " , end="" ) else : print(chr(i), end="" ) print(" ou)" ) local_file.close() except Exception as e: print(e) print("(newline ou)" ) print("(close-output-port ou)" ) except Exception as e: print(e)
Reference
R5RS