蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 Perl 文件打开模式、sysopen 标志、指针定位与文件测试操作符

PYTHONWindows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。explore-files.py
explore-files.py219 行
"""Offline Perl 5 semantic verification lab for Chapter 17 (files)."""
import json
import os
import stat
import tempfile
from pathlib import Path

VERSION = "CPython 3.12.14 offline Perl 5 semantic verifier (perl absent)"


def case_open_modes_and_sysopen_flags():
    with tempfile.TemporaryDirectory() as td:
        p = Path(td) / "modes.txt"
        # > write (truncate/create)
        p.write_text("line1\n", encoding="utf-8")
        # >> append
        with p.open("a", encoding="utf-8") as f:
            f.write("line2\n")
        after_append = p.read_text(encoding="utf-8")
        # +< read-write without truncation
        with p.open("r+", encoding="utf-8") as f:
            head = f.readline()
            f.seek(0, os.SEEK_END)
            f.write("line3\n")
        after_rw = p.read_text(encoding="utf-8")
        # sysopen O_CREAT | O_EXCL | O_RDWR semantics via os.open
        fd = os.open(str(Path(td) / "exclusive.txt"), os.O_CREAT | os.O_EXCL | os.O_RDWR)
        os.write(fd, b"sysopen-ok")
        os.close(fd)
        excl_blocked = False
        try:
            os.open(str(Path(td) / "exclusive.txt"), os.O_CREAT | os.O_EXCL | os.O_RDWR)
        except FileExistsError:
            excl_blocked = True
        default_octal_perms = 0o666
    expected = {
        "after_append": "line1\nline2\n",
        "rw_first_line": "line1\n",
        "after_rw": "line1\nline2\nline3\n",
        "o_excl_blocks_existing": True,
        "default_perms_octal_int": 438,
    }
    actual = {
        "after_append": after_append,
        "rw_first_line": head,
        "after_rw": after_rw,
        "o_excl_blocks_existing": excl_blocked,
        "default_perms_octal_int": default_octal_perms,
    }
    return {
        "name": "open_modes_and_sysopen_flags",
        "summary": "验证 open 的 >、>>、+< 模式与 sysopen 的 O_CREAT|O_EXCL|O_RDWR 标志及默认八进制 0666 权限",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_line_scalar_list_getc_read_print():
    with tempfile.TemporaryDirectory() as td:
        p = Path(td) / "import.txt"
        p.write_text("1\n2\n3\n", encoding="utf-8")
        with p.open("r", encoding="utf-8") as f:
            scalar_first = f.readline()
            rest_list = f.readlines()
        # getc single char + EOF
        with p.open("r", encoding="utf-8") as f:
            c1 = f.read(1)
            c2 = f.read(1)
            f.seek(0, os.SEEK_END)
            eof_char = f.read(1) or None
        # read(FH, $buf, $len, $offset) simulation
        bin_p = Path(td) / "bin.dat"
        bin_p.write_bytes(b"ABCDEFGHIJ")
        buf = bytearray(b"xx")
        with bin_p.open("rb") as f:
            chunk = f.read(4)
            offset = 2
            buf[offset : offset + len(chunk)] = chunk
            bytes_read = len(chunk)
    expected = {
        "scalar_first": "1\n",
        "rest_list": ["2\n", "3\n"],
        "getc_first": "1",
        "getc_second": "\n",
        "getc_eof_is_undef": True,
        "read_bytes": 4,
        "buf_with_offset": "xxABCD",
    }
    actual = {
        "scalar_first": scalar_first,
        "rest_list": rest_list,
        "getc_first": c1,
        "getc_second": c2,
        "getc_eof_is_undef": eof_char is None,
        "read_bytes": bytes_read,
        "buf_with_offset": buf.decode("ascii"),
    }
    return {
        "name": "line_scalar_list_getc_read_print",
        "summary": "验证 <FILEHANDLE> 标量/列表上下文、getc 单字符与 EOF(undef) 及 read 带偏移量二进制读取",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_copy_rename_unlink_tell_seek():
    with tempfile.TemporaryDirectory() as td:
        src = Path(td) / "file1.txt"
        dst = Path(td) / "file2.txt"
        renamed = Path(td) / "file3.txt"
        payload = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"
        src.write_bytes(payload.encode("utf-8"))
        # Copy line by line preserving LF byte offsets
        with src.open("r", encoding="utf-8", newline="") as r, dst.open("w", encoding="utf-8", newline="") as w:
            for line in r:
                w.write(line)
        # tell and seek with whence 0, 1, 2
        with dst.open("rb") as f:
            f.seek(10, 0)
            pos_after_set = f.tell()
            seg1 = f.read(4).decode("ascii")
            f.seek(2, 1)
            pos_after_cur = f.tell()
            seg2 = f.read(3).decode("ascii")
            f.seek(-5, 2)
            seg3 = f.read(4).decode("ascii")
        # rename & unlink
        os.rename(dst, renamed)
        renamed_exists = renamed.exists() and not dst.exists()
        os.unlink(renamed)
        unlinked = not renamed.exists()
    expected = {
        "pos_after_set": 10,
        "seg1": "ABCD",
        "pos_after_cur": 16,
        "seg2": "GHI",
        "seg3": "WXYZ",
        "renamed_ok": True,
        "unlinked_ok": True,
    }
    actual = {
        "pos_after_set": pos_after_set,
        "seg1": seg1,
        "pos_after_cur": pos_after_cur,
        "seg2": seg2,
        "seg3": seg3,
        "renamed_ok": renamed_exists,
        "unlinked_ok": unlinked,
    }
    return {
        "name": "copy_rename_unlink_tell_seek",
        "summary": "验证逐行文件拷贝、rename、unlink 以及 tell/seek(0/1/2) 字节定位行为",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_file_test_operators_and_stat_cache():
    with tempfile.TemporaryDirectory() as td:
        txt = Path(td) / "sample.txt"
        empty = Path(td) / "empty.txt"
        sub = Path(td) / "subdir"
        sub.mkdir()
        txt.write_bytes(b"www.example.com")
        empty.write_bytes(b"")
        st_txt = os.stat(txt)  # simulates Perl _ stat cache
        raw = txt.read_bytes()
        is_text = b"\x00" not in raw
        expected = {
            "exists_e": True,
            "plain_file_f": True,
            "dir_d_on_file": False,
            "dir_d_on_subdir": True,
            "size_s": 15,
            "empty_z_on_txt": False,
            "empty_z_on_empty": True,
            "text_T": True,
            "binary_B": False,
            "readable_r": True,
            "writable_w": True,
        }
        actual = {
            "exists_e": txt.exists(),
            "plain_file_f": stat.S_ISREG(st_txt.st_mode),
            "dir_d_on_file": stat.S_ISDIR(st_txt.st_mode),
            "dir_d_on_subdir": sub.is_dir(),
            "size_s": st_txt.st_size,
            "empty_z_on_txt": st_txt.st_size == 0,
            "empty_z_on_empty": os.stat(empty).st_size == 0,
            "text_T": is_text,
            "binary_B": not is_text,
            "readable_r": os.access(txt, os.R_OK),
            "writable_w": os.access(txt, os.W_OK),
        }
    return {
        "name": "file_test_operators_and_stat_cache",
        "summary": "验证 -e/-f/-d/-s/-z/-T/-B/-r/-w 文件测试操作符与下划线 _ stat 缓存复用语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_open_modes_and_sysopen_flags(),
        case_line_scalar_list_getc_read_print(),
        case_copy_rename_unlink_tell_seek(),
        case_file_test_operators_and_stat_cache(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。

入口文件:projects/perl-files-lab/explore-files.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-files.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Perl 5 语义验证器(本机未安装原生 perl 解释器)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Perl

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a2480.zip

下载课程关联工程包:Perl

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2490.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习