"""Offline Ruby 3.x semantic verification lab for Chapter 27 (input-output)."""
import io
import json
import os
import stat
import tempfile
from pathlib import Path
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"
def case_console_io_puts_print_putc_gets():
# Simulate Ruby Kernel#puts, print, putc, gets on in-memory IO streams
buf_puts = io.StringIO()
for v in ("This is variable one", "This is variable two"):
buf_puts.write(v + "\n")
buf_print = io.StringIO()
buf_print.write("Hello World")
buf_print.write("Good Morning")
buf_putc = io.StringIO()
s = "Hello Ruby!"
buf_putc.write(s[0])
fake_stdin = io.StringIO("This is entered value\n")
val = fake_stdin.readline()
expected = {
"puts_out": "This is variable one\nThis is variable two\n",
"print_out": "Hello WorldGood Morning",
"putc_out": "H",
"gets_val": "This is entered value\n",
}
actual = {
"puts_out": buf_puts.getvalue(),
"print_out": buf_print.getvalue(),
"putc_out": buf_putc.getvalue(),
"gets_val": val,
}
return {
"name": "console_io_puts_print_putc_gets",
"summary": "核验 puts 自动换行、print 连续输出、putc 仅输出首字符与 gets 读取含换行符的一行",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_file_modes_and_sys_rw_ops():
with tempfile.TemporaryDirectory() as tmp:
p = Path(tmp) / "input.txt"
text = "This is a simple text file for testing purpose."
p.write_text(text, encoding="utf-8")
# sysread(20) equivalent: read first 20 bytes and advance cursor to byte 20 (21st byte)
with p.open("rb") as fh:
head20 = fh.read(20).decode("utf-8")
pos_after = fh.tell()
# r+ syswrite("ABCDEF"), rewind, each_byte with '.' separator
with p.open("r+b") as fh:
fh.write(b"ABCDEF")
fh.seek(0)
raw = fh.read()
dotted = "".join(chr(b) + "." for b in raw)
# IO.readlines & IO.foreach on multi-line file
ml = Path(tmp) / "lines.txt"
ml.write_text("line1\nline2\n", encoding="utf-8")
lines_arr = ml.read_text(encoding="utf-8").splitlines(keepends=True)
foreach_lines = [ln.strip() for ln in lines_arr]
expected = {
"head20": "This is a simple tex",
"pos_after": 20,
"dotted_prefix": "A.B.C.D.E.F.s. .a. .",
"readlines_count": 2,
"foreach_lines": ["line1", "line2"],
}
actual = {
"head20": head20,
"pos_after": pos_after,
"dotted_prefix": dotted[:20],
"readlines_count": len(lines_arr),
"foreach_lines": foreach_lines,
}
return {
"name": "file_modes_and_sys_rw_ops",
"summary": "在隔离临时目录核验 r/r+/w 模式、定长读取指针前移、r+ 覆写前 6 字节与逐行/逐字节读取",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_file_queries_chmod_and_rename():
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
f1 = root / "test1.txt"
f2 = root / "test2.txt"
f1.write_text("ruby-io", encoding="utf-8")
empty = root / "empty.txt"
empty.write_bytes(b"")
# Rename & query predicates
f1.rename(f2)
st = f2.stat()
mode_octal = oct(0o755)
expected = {
"f1_exists": False,
"f2_is_file": True,
"root_is_dir": True,
"empty_is_zero": True,
"f2_size": 7,
"ftype_regular": "file",
"has_timestamps": True,
"chmod_0755_octal": "0o755",
}
actual = {
"f1_exists": f1.exists(),
"f2_is_file": f2.is_file(),
"root_is_dir": root.is_dir(),
"empty_is_zero": empty.stat().st_size == 0,
"f2_size": st.st_size,
"ftype_regular": "file" if stat.S_ISREG(st.st_mode) else "other",
"has_timestamps": st.st_mtime > 0 and st.st_atime > 0 and st.st_ctime > 0,
"chmod_0755_octal": mode_octal,
}
f2.unlink()
return {
"name": "file_queries_chmod_and_rename",
"summary": "核验 File.rename/delete、exist?/file?/directory?/zero?/size?/ftype/mtime 及八进制权限掩码 0755",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_dir_ops_and_tempfile():
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
sub = base / "mynewdir"
sub.mkdir()
(sub / "a.rb").write_text("puts 1\n", encoding="utf-8")
entries = sorted(os.listdir(sub))
globbed = [p.name for p in sub.glob("*")]
(sub / "a.rb").unlink()
sub.rmdir()
# Tempfile lifecycle
with tempfile.NamedTemporaryFile(prefix="tingtong", dir=tmp, delete=False, mode="w", encoding="utf-8") as tf:
tf.write("Hello\n")
tf_path = Path(tf.name)
tf_exists_before = tf_path.exists()
tf_content = tf_path.read_text(encoding="utf-8")
tf_path.unlink()
tf_exists_after = tf_path.exists()
expected = {
"entries": ["a.rb"],
"globbed": ["a.rb"],
"sub_removed": True,
"tempfile_content": "Hello\n",
"tempfile_cleanup": [True, False],
}
actual = {
"entries": entries,
"globbed": globbed,
"sub_removed": not sub.exists(),
"tempfile_content": tf_content,
"tempfile_cleanup": [tf_exists_before, tf_exists_after],
}
return {
"name": "dir_ops_and_tempfile",
"summary": "核验 Dir.mkdir/entries/glob/delete 与 tmpdir/Tempfile 临时文件创建及清理",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_console_io_puts_print_putc_gets(),
case_file_modes_and_sys_rw_ops(),
case_file_queries_chmod_and_rename(),
case_dir_ops_and_tempfile(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
入口文件:projects/ruby-input-output-lab/explore-input-output.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-input-output.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联45章) · 含当前章节或实例 · mbskycom202612a2434.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2455.zip