"""蓝色天空网 mbsky.com:仅在本次新建目录运行OS接口;不动用户数据/配置。"""
from pathlib import Path
import os,sys,tempfile,stat,subprocess,io
P=Path(__file__).resolve().parent;sys.path.insert(0,str(P))
from mbsky_pychecks import Checks
def main():
c=Checks();root=P/"_runtime-work";root.mkdir(exist_ok=True);initial=Path.cwd();capability={}
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","startfile"]:
capability[name]=dict(available=hasattr(os,name),executed=False,status="present_not_executed"if hasattr(os,name)else"unavailable_on_this_host")
with tempfile.TemporaryDirectory(prefix="os-files-",dir=root)as folder:
work=Path(folder).resolve();assert work.is_relative_to(root.resolve())
try:
os.chdir(work);c.eq("chdir actual cwd",Path(os.getcwd()).resolve()==work,True)
c.eq("getcwd is str",type(os.getcwd())is str,True);c.eq("getcwdb is bytes",type(os.getcwdb())is bytes,True)
c.eq("getcwdb decodes actual cwd",os.fsdecode(os.getcwdb()),os.getcwd());c.eq("cwd differs from script folder",Path.cwd()!=P,True)
c.eq("pardir string constant",os.pardir,"..");c.eq("pardir not callable",callable(os.pardir),False)
c.eq("path parent normalization",Path(os.path.abspath(os.pardir))==work.parent,True)
os.mkdir("one");c.eq("mkdir creates directory",Path("one").is_dir(),True);c.raises("mkdir existing fails",FileExistsError,lambda:os.mkdir("one"))
c.eq("mkdir return independent deletion",os.rmdir("one"),None);c.eq("rmdir deleted empty",Path("one").exists(),False)
os.makedirs("tree/branch/leaf");c.eq("makedirs intermediate actual",Path("tree/branch/leaf").is_dir(),True)
c.eq("makedirs exist_ok",os.makedirs("tree/branch/leaf",exist_ok=True),None)
os.removedirs("tree/branch/leaf");c.eq("removedirs prunes empty parents",Path("tree").exists(),False)
os.mkdir("nonempty");Path("nonempty/keep").write_bytes(b"k")
try:os.rmdir("nonempty")
except OSError as exc:c.eq("rmdir nonempty refused",Path("nonempty/keep").read_bytes(),b"k");nonempty_error=type(exc).__name__
else:raise AssertionError("removed nonempty directory")
os.remove("nonempty/keep");os.rmdir("nonempty")
Path("alpha.txt").write_bytes(b"ABC");os.mkdir("dir")
c.eq("listdir actual names",sorted(os.listdir()),["alpha.txt","dir"])
c.eq("listdir explicit same names",sorted(os.listdir(work)),["alpha.txt","dir"])
c.eq("access existence",os.access("alpha.txt",os.F_OK),True);c.eq("access missing",os.access("missing",os.F_OK),False)
os.rename("alpha.txt","beta.txt");c.eq("rename content preserved",Path("beta.txt").read_bytes(),b"ABC");c.eq("rename old absent",Path("alpha.txt").exists(),False)
Path("occupied.txt").write_bytes(b"old")
if os.name=="nt":c.raises("Windows rename existing refusal",FileExistsError,lambda:os.rename("beta.txt","occupied.txt"))
else:
os.rename("beta.txt","occupied.txt");Path("beta.txt").write_bytes(b"ABC")
c.eq("replace overwrites own destination",os.replace("beta.txt","occupied.txt"),None);c.eq("replace actual destination bytes",Path("occupied.txt").read_bytes(),b"ABC")
os.makedirs("old/inner");Path("old/inner/data").write_bytes(b"R")
os.renames("old/inner/data","new/deep/renamed");c.eq("renames new parents content",Path("new/deep/renamed").read_bytes(),b"R")
c.eq("renames old empty parents removed",Path("old").exists(),False)
path=work/"occupied.txt";c.eq("stat file size",os.stat(path).st_size,3);c.eq("stat regular mode",stat.S_ISREG(os.stat(path).st_mode),True)
c.eq("lstat regular file",stat.S_ISREG(os.lstat(path).st_mode),True)
os.utime(path,ns=(1600000000000000000,1600000001000000000));c.eq("utime sets mtime ns",os.stat(path).st_mtime_ns,1600000001000000000)
c.eq("utime return None",os.utime(path,ns=(1600000000000000000,1600000001000000000)),None)
try:
os.chmod(path,stat.S_IREAD);c.eq("chmod clears readonly write bit",bool(os.stat(path).st_mode&stat.S_IWRITE),False)
finally:os.chmod(path,stat.S_IREAD|stat.S_IWRITE)
c.eq("chmod restores write bit",bool(os.stat(path).st_mode&stat.S_IWRITE),True)
link=work/"hard.txt";c.eq("link returns None",os.link(path,link),None);c.eq("link same file",os.path.samefile(path,link),True)
with open(link,"ab")as f:f.write(b"D")
c.eq("hard link shared content",path.read_bytes(),b"ABCD");os.unlink(link);c.eq("unlink link keeps target",path.read_bytes(),b"ABCD")
symbolic=work/"sym.txt"
try:os.symlink(path,symbolic)
except OSError as exc:symlink=dict(status="creation_not_permitted_or_unsupported",error=type(exc).__name__,winerror=getattr(exc,"winerror",None),runtime_accepted=False)
else:
c.eq("symlink lstat link",stat.S_ISLNK(os.lstat(symbolic).st_mode),True)
c.eq("symlink stat follows target",os.stat(symbolic).st_size,4)
target=os.readlink(symbolic);c.eq("readlink target string type",type(target)is str,True);c.eq("readlink resolves target",os.path.samefile(target,path),True)
if os.name=="nt":c.eq("readlink Windows namespace prefix",target.startswith("\\\\?\\"),True)
c.eq("readlink not file content",Path(symbolic).read_bytes(),b"ABCD")
symbolic.unlink();symlink=dict(status="owned_symlink_actual_observed",runtime_accepted=True)
descriptors=work/"fd.bin";fd=os.open(descriptors,os.O_CREAT|os.O_TRUNC|os.O_RDWR|os.O_BINARY,0o600)
try:
c.eq("open fd integer",type(fd)is int,True);c.eq("write bytes length",os.write(fd,b"abcdef"),6)
c.eq("fstat current bytes",os.fstat(fd).st_size,6);c.eq("isatty own regular fd",os.isatty(fd),False)
c.eq("lseek absolute",os.lseek(fd,2,os.SEEK_SET),2);c.eq("read byte type",os.read(fd,1),b"c")
c.eq("lseek relative",os.lseek(fd,-1,os.SEEK_CUR),2)
c.eq("lseek from end",os.lseek(fd,-2,os.SEEK_END),4);c.eq("read maximum bytes",os.read(fd,10),b"ef");c.eq("read EOF empty bytes",os.read(fd,1),b"")
c.raises("write rejects text str",TypeError,lambda:os.write(fd,"text"))
copyfd=os.dup(fd)
try:
os.lseek(copyfd,0,os.SEEK_SET);c.eq("dup shares offset",os.read(fd,1),b"a")
finally:os.close(copyfd)
c.raises("close copied descriptor",OSError,lambda:os.fstat(copyfd))
dst=os.open(work/"dest.bin",os.O_CREAT|os.O_TRUNC|os.O_RDWR|os.O_BINARY,0o600)
try:
c.eq("dup2 destination integer",os.dup2(fd,dst),dst);os.lseek(dst,1,os.SEEK_SET);c.eq("dup2 shared offset",os.read(fd,1),b"b")
c.eq("dup2 same data",os.fstat(dst).st_size,6)
finally:os.close(dst)
owned=os.dup(fd);c.eq("closerange own one fd",os.closerange(owned,owned+1),None);c.raises("closerange fd actually closed",OSError,lambda:os.fstat(owned))
c.eq("closerange ignores already closed",os.closerange(owned,owned+1),None)
c.eq("ftruncate shrink return",os.ftruncate(fd,2),None);c.eq("ftruncate shrunk actual size",os.fstat(fd).st_size,2)
os.ftruncate(fd,5);c.eq("ftruncate growth size",os.fstat(fd).st_size,5);os.lseek(fd,0,0);c.eq("ftruncate growth keeps prefix zeros",os.read(fd,10),b"ab\0\0\0")
c.eq("fsync returns None",os.fsync(fd),None)
finally:os.close(fd)
c.raises("close actual descriptor",OSError,lambda:os.fstat(fd))
fd=os.open(path,os.O_RDONLY|os.O_BINARY)
with os.fdopen(fd,"rb")as wrapper:c.eq("fdopen bytes contents",wrapper.read(),b"ABCD")
c.raises("fdopen context closes fd",OSError,lambda:os.fstat(fd))
r,w=os.pipe()
try:
c.eq("pipe two different descriptors",r!=w,True);c.eq("pipe writes actual bytes",os.write(w,b"sky"),3);c.eq("pipe reads actual bytes",os.read(r,3),b"sky")
finally:os.close(w);os.close(r)
envkey="MBSKY_TUTORIAL_OS_EXAMPLE";old=os.environ.get(envkey)
try:
os.environ.pop(envkey,None);c.eq("getenv absent None",os.getenv(envkey),None);c.eq("getenv fallback",os.getenv(envkey,"fallback"),"fallback")
os.environ[envkey]="mbsky.com";c.eq("getenv own value",os.getenv(envkey),"mbsky.com")
finally:
if old is None:os.environ.pop(envkey,None)
else:os.environ[envkey]=old
c.eq("environment owned key restored",os.environ.get(envkey),old)
exit_command=subprocess.list2cmdline([sys.executable,"-I","-B","-c","import sys;sys.exit(7)"])
status=os.system(exit_command);c.eq("system fixed child status",status,7 if os.name=="nt"else 7<<8)
command=subprocess.list2cmdline([sys.executable,"-I","-B","-c","print('mbsky.com')"])
with os.popen(command)as pipe:c.eq("popen fixed child stdout",pipe.read(),"mbsky.com\n")
output=subprocess.run([sys.executable,"-I","-B","-c","print('mbsky.com')"],capture_output=True,text=True,timeout=5);c.eq("subprocess preferred argv output",output.stdout,"mbsky.com\n");c.eq("subprocess child exit",output.returncode,0)
os.makedirs("walk/branch");Path("walk/root.txt").write_bytes(b"r");Path("walk/branch/leaf.txt").write_bytes(b"l")
actual=[(Path(base).relative_to(Path("walk")).as_posix(),sorted(dirs),sorted(files))for base,dirs,files in os.walk("walk")]
c.eq("walk structured triples",actual,[(".",["branch"],["root.txt"]),("branch",[],["leaf.txt"])])
bottom=[Path(base).relative_to(Path("walk")).as_posix()for base,_,_ in os.walk("walk",topdown=False)];c.eq("walk bottom up actual order",bottom,["branch","."])
c.eq("path basename",os.path.basename(path),"occupied.txt");c.eq("path isfile",os.path.isfile(path),True);c.eq("path exists missing",os.path.exists(work/"missing"),False)
for name in ["stat_float_times","tempnam","tmpfile","tmpnam"]:c.eq("historical removed absent "+name,hasattr(os,name),False)
Path("delete.txt").write_bytes(b"d");c.eq("remove file returns None",os.remove("delete.txt"),None);c.eq("remove file absent",Path("delete.txt").exists(),False);c.raises("remove missing FileNotFound",FileNotFoundError,lambda:os.remove("delete.txt"))
os.mkdir("unlink-dir")
try:os.remove("unlink-dir")
except OSError as exc:remove_dir_error=type(exc).__name__;c.eq("remove directory refused",Path("unlink-dir").is_dir(),True)
else:raise AssertionError("file remove deleted directory")
os.rmdir("unlink-dir")
with tempfile.TemporaryFile(mode="w+b",dir=work)as f:f.write(b"sky");f.seek(0);c.eq("tempfile old tmpfile alternative",f.read(),b"sky")
with tempfile.NamedTemporaryFile(dir=work)as f:c.eq("namedtemp old name alternative exists",Path(f.name).exists(),True)
finally:os.chdir(initial)
c.eq("cwd restored before cleanup",str(Path.cwd()),str(initial));c.eq("own os temp removed",work.exists(),False)
c.finish("python3-os-file-methods",host=os.name,capability_inventory=capability,symlink=symlink,nonempty_error=nonempty_error,remove_directory_error=remove_dir_error,source_scripts_executed=False,source_shell_command_never_executed=True,fsync_not_power_failure_proof=True,unverified_unix_or_desktop_not_accepted=True)
if __name__=="__main__":main()
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地 Python 环境
入口文件:projects/python-lab/python3-os-file-methods.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python3-os-file-methods.py,或下载右侧课程工程包。 - 确认本地已准备 本地 Python 环境。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip