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

运行文件对象的参数、描述符及定位实验

PYTHONWindows CPython 3.12legacy-stream-methods-lab.py
legacy-stream-methods-lab.py188 行
import json


def report(name, value):
    print(json.dumps([name, value], ensure_ascii=True))


def error_name(action):
    try:
        action()
    except (AttributeError, IndexError, KeyError, NameError, TypeError, ValueError) as error:
        return type(error).__name__
    return None


import io
import os
import subprocess
import sys
from pathlib import Path
from tempfile import TemporaryDirectory


def failure(action):
    try:
        action()
    except (OSError, ValueError, TypeError, StopIteration) as error:
        return type(error).__name__
    return None


with TemporaryDirectory(prefix="mbsky-stream-", dir=Path.cwd()) as name:
    root = Path(name).resolve()
    path = root/"sample.txt"
    path.write_bytes("北\r\n南\r末\n".encode("utf8"))
    with open(path, encoding="utf8", newline=None) as stream:
        default_mode = stream.mode
        translated = stream.read()
    with open(path, "rt", encoding="utf8", newline="") as stream:
        preserved = stream.read()
    with open(path, "rb", buffering=0) as stream:
        unbuffered = type(stream).__name__
        first_two = stream.read(2).hex()
    with open(path, "rb", buffering=8) as stream:
        buffered = type(stream).__name__
    with open(root/"line.txt", "w", encoding="utf8", buffering=1, newline="") as stream:
        line_buffer = stream.line_buffering
        stream.write("北\n")
        line_seen = (root/"line.txt").read_bytes().hex()

    invalid = root/"invalid.txt"
    invalid.write_bytes(b"X\xffZ")
    def decoded(errors):
        with open(invalid, encoding="utf8", errors=errors) as stream:
            return stream.read()

    def try_open(file, mode, **options):
        with open(file, mode, **options):
            return True

    fd = os.open(path, os.O_RDONLY | os.O_BINARY)
    try:
        with open(fd, "rb", closefd=False) as wrapper:
            fd_content = wrapper.read(2).hex()
        fd_retained = os.fstat(fd).st_size == path.stat().st_size
    finally:
        os.close(fd)
    fd_owned = os.open(path, os.O_RDONLY | os.O_BINARY)
    with open(fd_owned, "rb", closefd=True) as stream:
        assert stream.fileno() == fd_owned
    fd_closed = failure(lambda: os.fstat(fd_owned))
    calls = []
    def custom_opener(file, flags):
        calls.append([Path(file).name, (flags & (os.O_WRONLY|os.O_RDWR))==os.O_RDONLY])
        return os.open(file, flags)

    with open(path, "rb", opener=custom_opener) as custom:
        custom_fd=custom.fileno()
        custom_bytes=custom.read(2).hex()
    closed_after_opener=failure(lambda: os.fstat(custom_fd))
    report("open_arguments", {
        "file": [path.name,fd_content,failure(lambda: try_open(root/"missing.txt","r"))],
        "mode": [default_mode,translated],
        "buffering": [unbuffered,buffered,line_buffer,line_seen,
                      failure(lambda: try_open(path,"r",buffering=0))],
        "encoding": ["北".encode("utf8").hex(),failure(lambda: try_open(path,"rb",encoding="utf8"))],
        "errors": [failure(lambda: decoded("strict")),decoded("replace"),decoded("ignore")],
        "newline": [translated,preserved],
        "closefd": [fd_retained,fd_closed,failure(lambda: try_open(path,"rb",closefd=False))],
        "opener": [calls,custom_bytes,closed_after_opener],
    })

    exclusive=root/"exclusive.txt"
    first=try_open(exclusive,"x")
    modes={"t":[failure(lambda:try_open(path,"t")),translated],
           "b":[failure(lambda:try_open(path,"b")),first_two],
           "+":failure(lambda:try_open(path,"+")),
           "U":[failure(lambda:try_open(path,"U")),translated],
           "x":[first,failure(lambda:try_open(exclusive,"x"))]}
    for mode in ("r","rb","r+","rb+","w","wb","w+","wb+","a","ab","a+","ab+"):
        old=root/("old-"+mode)
        new=root/("new-"+mode)
        old.write_bytes(b"abc")
        binary="b" in mode
        options={} if binary else {"encoding":"utf8","newline":""}
        with open(old,mode,**options) as stream:
            start=stream.tell()
            read,write=stream.readable(),stream.writable()
            empty=old.stat().st_size==0
            stream.seek(0)
            if write:
                stream.write(b"Z" if binary else "Z")
        missing=failure(lambda:try_open(new,mode))
        modes[mode]=[read,write,empty,start,old.read_bytes().decode("ascii"),missing,new.exists()]
    report("modes",modes)

    output=root/"output.bin"
    with open(output,"wb",buffering=8) as stream:
        stream.write(b"xy")
        before=output.read_bytes().hex()
        stream.flush()
        after=output.read_bytes().hex()
        ordinary_fd=stream.fileno()
        size=os.fstat(ordinary_fd).st_size
        is_terminal=stream.isatty()
    stream.close()
    closed=[stream.closed,output.read_bytes().hex(),failure(lambda:stream.write(b"q"))]
    pipe=subprocess.run([sys.executable,"-I","-B","-c","import sys;print(sys.stdin.isatty())"],
                        input=b"",capture_output=True,check=True)
    assert not pipe.stderr
    with open(path,"r",encoding="utf8",newline=None) as stream:
        first_line=next(stream)
        second_line=next(stream)
        third_line=next(stream)
        exhausted=failure(lambda:next(stream))
    with open(path,"r",encoding="utf8",newline=None) as stream:
        by_chars=[stream.read(2),stream.read(-1),stream.read()]
    with open(path,"rb") as stream:
        by_bytes=[stream.read(2).hex(),len(stream.read())]
    with open(path,"r",encoding="utf8",newline=None) as stream:
        line_fragments=[stream.readline(1),stream.readline(),stream.readline(),stream.readline(),stream.readline()]
    hint_file=root/"lines.txt"
    hint_file.write_bytes(b"a\nbbbb\nc\n")
    with open(hint_file,"rb") as stream:
        with_hint=[line.decode("ascii") for line in stream.readlines(3)]
        remaining_lines=[line.decode("ascii") for line in stream.readlines()]
    with open(path,"r",encoding="utf8",newline=None) as stream:
        stream.read(2)
        mark=stream.tell()
        point=stream.read(1)
        stream.seek(mark)
        returned=stream.read(1)
        text_seek=failure(lambda:stream.seek(-1,1))
    with open(path,"rb") as stream:
        positions=[stream.seek(2,os.SEEK_SET),stream.seek(1,os.SEEK_CUR),
                   stream.seek(-1,os.SEEK_END),stream.tell()]
    shortened=root/"short.bin"
    shortened.write_bytes(b"abcdef")
    with open(shortened,"rb+") as stream:
        stream.seek(3)
        explicit=stream.truncate(5)
        same_after_explicit=stream.tell()
        default=stream.truncate()
        same_after_default=stream.tell()
    written=root/"written.txt"
    with open(written,"w",encoding="utf8",newline="") as stream:
        amount=stream.write("北站")
    with open(written,"ab") as stream:
        byte_amount=stream.write("北站".encode("utf8"))
    joined=root/"joined.txt"
    with open(joined,"w",encoding="utf8",newline="") as stream:
        lines_return=stream.writelines(iter(["北","南\n","西"]))
    report("methods",{
        "file.close":closed,
        "file.flush":[before,after],
        "file.fileno":[isinstance(ordinary_fd,int),size,failure(io.BytesIO().fileno)],
        "file.isatty":[is_terminal,pipe.stdout.decode().strip()],
        "file.next":[first_line,second_line,third_line,exhausted,hasattr(io.StringIO(),"next")],
        "file.read":[by_chars,by_bytes],
        "file.readline":line_fragments,
        "file.readlines":[with_hint,remaining_lines],
        "file.seek":[positions,text_seek],
        "file.tell":[isinstance(mark,int),point,returned],
        "file.truncate":[explicit,same_after_explicit,default,same_after_default,shortened.read_bytes().decode("ascii")],
        "file.write":[amount,byte_amount,written.read_bytes().hex()],
        "file.writelines":[lines_return,joined.read_text(encoding="utf8")],
    })
本例需在 Windows CPython 3.12 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPython 3.12

入口文件:projects/python-legacy-lab/legacy-stream-methods-lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 legacy-stream-methods-lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPython 3.12。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python2.x

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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