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 os
import stat
import subprocess
import sys
import tempfile
from pathlib import Path
def error(action):
try:
action()
except (OSError, ValueError, TypeError) as exc:
return type(exc).__name__
return None
def descriptor_cases(root, result):
path = root / "events.bin"
flags = os.O_RDWR | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0)
fd = os.open(path, flags, 0o600)
result["os.open"] = [isinstance(fd, int), error(lambda: os.open(path, flags))]
try:
result["os.write"] = [os.write(fd, b"abcdef"), error(lambda: os.write(fd, "abc"))]
result["os.lseek"] = [
os.lseek(fd, 1, os.SEEK_SET),
os.lseek(fd, 1, os.SEEK_CUR),
os.lseek(fd, -1, os.SEEK_END),
]
result["os.read"] = [os.read(fd, 9).hex(), os.read(fd, 9).hex()]
os.lseek(fd, 0, os.SEEK_SET)
duplicate = os.dup(fd)
try:
result["os.dup"] = [duplicate != fd, os.get_inheritable(duplicate),
os.read(duplicate, 2).hex(), os.read(fd, 1).hex()]
finally:
os.close(duplicate)
other = os.open(root / "other.bin", flags, 0o600)
try:
os.write(other, b"x")
result["os.dup2"] = [os.fstat(other).st_size,
os.dup2(fd, other, inheritable=False) == other,
os.get_inheritable(other), os.read(other, 1).hex(),
os.lseek(fd, 0, os.SEEK_CUR)]
finally:
os.close(other)
result["os.fstat"] = [os.fstat(fd).st_size, stat.S_ISREG(os.fstat(fd).st_mode)]
result["os.isatty"] = [os.isatty(fd)]
os.ftruncate(fd, 3)
short = os.fstat(fd).st_size
os.ftruncate(fd, 6)
result["os.ftruncate"] = [short, os.fstat(fd).st_size, os.lseek(fd, 0, os.SEEK_CUR)]
os.lseek(fd, 0, os.SEEK_SET)
result["os.ftruncate"].append(os.read(fd, 8).hex())
result["os.fsync"] = [os.fsync(fd), path.read_bytes().hex()]
finally:
os.close(fd)
result["os.close"] = error(lambda: os.fstat(fd))
owned = os.open(path, os.O_RDONLY | getattr(os, "O_BINARY", 0))
with os.fdopen(owned, "rb") as stream:
prefix = stream.read(3)
result["os.fdopen"] = [prefix.hex(), stream.closed, error(lambda: os.fstat(owned))]
left, hole, right = [os.open(path, os.O_RDONLY) for _ in range(3)]
try:
if [left + 1, left + 2] != [hole, right]:
raise RuntimeError("expected consecutive owned descriptors for this example")
os.close(hole)
os.closerange(left, right)
result["os.closerange"] = [error(lambda: os.fstat(left)),
error(lambda: os.fstat(hole)), os.fstat(right).st_size]
finally:
for number in (left, hole, right):
try:
os.close(number)
except OSError:
pass
read_end, write_end = os.pipe()
try:
result["os.isatty"].extend([os.isatty(read_end), os.isatty(write_end)])
count = os.write(write_end, b"gate")
finally:
os.close(write_end)
try:
try:
pipe_offset = os.lseek(read_end, 1, os.SEEK_SET)
except OSError as exc:
pipe_offset = type(exc).__name__
result["os.pipe"] = [count, pipe_offset, os.read(read_end, 20).hex(),
os.read(read_end, 20).hex()]
finally:
os.close(read_end)
def directory_cases(root, result):
base = root / "北站"
os.mkdir(base, 0o700)
result["os.mkdir"] = [base.is_dir(), error(lambda: os.mkdir(base)),
error(lambda: os.mkdir(base / "missing" / "leaf"))]
cwd = os.getcwd()
try:
os.chdir(base)
result["os.chdir"] = [Path.cwd().samefile(base),
error(lambda: os.chdir("missing"))]
result["os.getcwd"] = [Path(os.getcwd()).name, type(os.getcwd()).__name__]
result["os.getcwdu"] = [hasattr(os, "getcwdu"), Path(os.getcwd()).name]
finally:
os.chdir(cwd)
result["os.chdir"].append(os.getcwd() == cwd)
left = base / "east" / "leaf"
os.makedirs(left, mode=0o700)
result["os.makedirs"] = [left.is_dir(), error(lambda: os.makedirs(left)),
os.makedirs(left, exist_ok=True)]
(base / "west").mkdir()
guard = base / "guard.txt"
guard.write_bytes(b"guard")
(left / "n.txt").write_bytes(b"n")
result["os.listdir"] = [sorted(os.listdir(base)),
sorted(type(x).__name__ for x in os.listdir(os.fsencode(base)))]
result["os.path"] = [
os.path.basename(os.path.join(base, "guard.txt")),
os.path.isfile(guard), os.path.getsize(guard),
os.path.commonpath([str(base / "east"), str(base / "west")]) == str(base),
]
top_down = [Path(here).relative_to(base).as_posix()
for here, _, _ in os.walk(base)]
bottom_up = [Path(here).relative_to(base).as_posix()
for here, _, _ in os.walk(base, topdown=False)]
visited = []
for here, dirs, _ in os.walk(base):
dirs[:] = [name for name in dirs if name != "east"]
visited.append(Path(here).relative_to(base).as_posix())
failures = []
list(os.walk(base / "absent", onerror=lambda exc: failures.append(type(exc).__name__)))
result["os.walk"] = [top_down[0], sorted(top_down[1:]), bottom_up[-1],
bottom_up.index("east/leaf") < bottom_up.index("east"), visited, failures]
result["os.rmdir"] = [error(lambda: os.rmdir(left)), os.rmdir(base / "west"),
(base / "west").exists()]
result["os.remove"] = [error(lambda: os.remove(left)), os.remove(left / "n.txt"),
(left / "n.txt").exists()]
os.removedirs(left)
result["os.removedirs"] = [left.exists(), left.parent.exists(), base.is_dir()]
renamed = base / "new.txt"
os.rename(guard, renamed)
collision = base / "present.txt"
collision.write_bytes(b"present")
result["os.rename"] = [guard.exists(), renamed.read_bytes().hex(),
error(lambda: os.rename(renamed, collision)),
renamed.read_bytes().hex(), collision.read_bytes().hex()]
original = base / "move" / "old.txt"
original.parent.mkdir()
original.write_bytes(b"move")
target = base / "target" / "nested" / "new.txt"
os.renames(original, target)
result["os.renames"] = [original.parent.exists(), target.read_bytes().hex()]
def metadata_cases(root, result):
path = root / "payload.bin"
path.write_bytes(b"unit")
result["os.access"] = [os.access(path, os.F_OK), os.access(path, os.R_OK | os.W_OK),
os.access(root / "missing", os.F_OK)]
try:
os.chmod(path, stat.S_IREAD)
result["os.chmod"] = [os.access(path, os.W_OK), error(lambda: path.write_bytes(b"new"))]
finally:
os.chmod(path, stat.S_IREAD | stat.S_IWRITE)
result["os.chmod"].append(os.access(path, os.W_OK))
result["os.stat"] = [os.stat(path).st_size, stat.S_ISREG(os.stat(path).st_mode)]
timestamp = (1700000000000000000, 1700000002000000000)
changed = os.utime(path, ns=timestamp)
metadata = os.stat(path)
seconds = os.utime(path, (1700000010, 1700000020))
updated = os.stat(path)
result["os.utime"] = [changed, metadata.st_atime_ns, metadata.st_mtime_ns,
seconds, updated.st_atime, updated.st_mtime]
result["os.stat_float_times"] = [hasattr(os, "stat_float_times"),
type(metadata.st_mtime).__name__, type(metadata.st_mtime_ns).__name__]
hard = root / "alias.bin"
os.link(path, hard)
result["os.link"] = [path.samefile(hard), os.stat(hard).st_nlink]
symlink = root / "pointer.bin"
try:
os.symlink(path.name, symlink)
except OSError as exc:
if getattr(exc, "winerror", None) not in (5, 1314):
raise
result["os.symlink"] = ["creation_denied", exc.winerror]
result["os.readlink"] = ["symbolic_link_creation_pending", error(lambda: os.readlink(path))]
result["os.lstat"] = [stat.S_ISREG(os.lstat(path).st_mode), "symbolic_link_creation_pending"]
else:
result["os.symlink"] = ["created", symlink.is_symlink(), symlink.samefile(path)]
result["os.readlink"] = [os.readlink(symlink), error(lambda: os.readlink(path))]
result["os.lstat"] = [stat.S_ISLNK(os.lstat(symlink).st_mode),
stat.S_ISREG(os.stat(symlink).st_mode)]
os.unlink(symlink)
result["os.symlink"].extend([os.path.lexists(symlink), path.exists()])
result["os.unlink"] = [os.unlink(path), path.exists(), hard.read_bytes().hex()]
def migration_cases(root, result):
fd, name = tempfile.mkstemp(dir=root, prefix="slot-")
try:
result["os.tempnam"] = [hasattr(os, "tempnam"), Path(name).name.startswith("slot-"),
os.path.isfile(name), os.fstat(fd).st_size]
finally:
os.close(fd)
os.unlink(name)
with tempfile.TemporaryFile(dir=root) as stream:
stream.write(b"session")
stream.seek(0)
result["os.tmpfile"] = [hasattr(os, "tmpfile"), isinstance(stream.fileno(), int),
stream.read().hex()]
result["os.tmpfile"].append(stream.closed)
with tempfile.NamedTemporaryFile(dir=root, delete=False) as stream:
named = Path(stream.name)
stream.write(b"trace")
try:
result["os.tmpnam"] = [hasattr(os, "tmpnam"), named.is_file(), named.read_bytes().hex()]
finally:
named.unlink()
result["os.tmpnam"].append(named.exists())
with os.popen("echo mbsky") as stream:
via_shell = stream.read().strip()
direct = subprocess.run([sys.executable, "-I", "-c", "print('mbsky')"], cwd=root,
check=True, capture_output=True, text=True, timeout=10)
result["os.popen"] = [via_shell, direct.stdout.strip(), direct.returncode]
with tempfile.TemporaryDirectory(prefix="mbsky-os-lab-") as scratch:
root = Path(scratch).resolve()
methods = {}
descriptor_cases(root, methods)
directory_cases(root, methods)
metadata_cases(root, methods)
migration_cases(root, methods)
for name in ['chflags', 'chown', 'chroot', 'fchdir', 'fchmod', 'fchown', 'fdatasync', 'fpathconf', 'fstatvfs', 'lchflags', 'lchmod', 'lchown', 'major', 'makedev', 'minor', 'mkfifo', 'mknod', 'openpty', 'pathconf', 'statvfs', 'tcgetpgrp', 'tcsetpgrp', 'ttyname']:
methods["os." + name] = ["available" if hasattr(os, name) else "unavailable", os.name]
report("methods", methods)
本例需在 Windows CPython 3.12,文件系统操作仅针对自建临时目录 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPython 3.12,文件系统操作仅针对自建临时目录
入口文件:projects/python-legacy-lab/legacy-os-files-lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
legacy-os-files-lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPython 3.12,文件系统操作仅针对自建临时目录。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202611a446.zip