"""蓝色天空网 mbsky.com — 格式化、临时文件和可信自建pickle。"""
from pathlib import Path
import sys,io,contextlib,tempfile,subprocess,math,pickle,pickletools,pprint
P=Path(__file__).resolve().parent;sys.path.insert(0,str(P))
from mbsky_pychecks import Checks
def input_mode():
try:value=input("请输入:")
except EOFError:print("EOF");return
print("记录:",value)
def main():
if len(sys.argv)>1 and sys.argv[1]=="--read-input":input_mode();return
if len(sys.argv)>1 and sys.argv[1]=="--stdout-demo":
written=sys.stdout.write("站台")
print("A","B",sep="-",end="!")
print(f"write={written}",file=sys.stderr)
return
c=Checks()
c.eq("str display","蓝色天空网",str("蓝色天空网"))
c.eq("repr quote escaped newline",repr("sky\n"),"'sky\\n'")
c.eq("float1 seventh",str(1/7),"0.14285714285714285")
c.eq("repr nested values",repr((32.5,40000,("HTML","CSS"))),"(32.5, 40000, ('HTML', 'CSS'))")
bare=subprocess.run([sys.executable,"-I","-B","-X","utf8","-c","3+4"],capture_output=True,text=True,encoding="utf8",timeout=5)
c.eq("bare expression script no output",bare.stdout,"")
repl=subprocess.run([sys.executable,"-I","-B","-X","utf8","-i","-c","pass"],input="3+4\nexit()\n",capture_output=True,text=True,encoding="utf8",timeout=5)
c.eq("real interactive expression display",repl.stdout,"7\n")
stream_sample=subprocess.run([sys.executable,"-I","-B","-X","utf8",__file__,"--stdout-demo"],
capture_output=True,timeout=5,check=True)
c.eq("stdout direct UTF-8 bytes",stream_sample.stdout,"站台A-B!".encode("utf-8"))
c.eq("stdout direct character count",stream_sample.stderr,b"write=2\n" if sys.platform!="win32" else b"write=2\r\n")
left=io.StringIO();right=io.StringIO()
with contextlib.redirect_stdout(left):
for x in range(1,11):
print(repr(x).rjust(2),repr(x*x).rjust(3),end=" ");print(repr(x*x*x).rjust(4))
with contextlib.redirect_stdout(right):
for x in range(1,11):print("{0:2d} {1:3d} {2:4d}".format(x,x*x,x*x*x))
c.eq("two table formatting methods exact",left.getvalue(),right.getvalue())
c.eq("table first row spaces",left.getvalue().splitlines()[0]," 1 1 1")
c.eq("table final row",left.getvalue().splitlines()[-1],"10 100 1000")
c.eq("table ten rows",len(left.getvalue().splitlines()),10)
c.eq("left align","sky".ljust(5),"sky ");c.eq("center align","sky".center(5)," sky ")
c.eq("zfill plain","12".zfill(5),"00012");c.eq("zfill sign","-3.14".zfill(7),"-003.14")
c.eq("small width no truncation","3.14159265359".zfill(5),"3.14159265359")
c.eq("brand basic format",'{}网址:"{}!"'.format("蓝色天空网","mbsky.com"),'蓝色天空网网址:"mbsky.com!"')
c.eq("format positional swap","{1} 和 {0}".format("HTML","CSS"),"CSS 和 HTML")
c.eq("format named","{name} {site}".format(name="蓝色天空网",site="mbsky.com"),"蓝色天空网 mbsky.com")
c.eq("format mixed named positional","{0},{1},{other}".format("HTML","CSS",other="Python"),"HTML,CSS,Python")
c.eq("format three conversions","{0!s}|{0!r}|{0!a}".format("天"),"天|'天'|'\\u5929'")
c.eq("PI3 decimal format","{0:.3f}".format(math.pi),"3.142")
c.eq("legacy percent3 decimal","%5.3f"%math.pi,"3.142")
c.eq("fstring main style",f"{math.pi:.3f}","3.142")
table={"HTML":1,"CSS":2,"Python":3}
c.eq("format minimum widths","{0:10} ==> {1:10d}".format("HTML",1),"HTML ==> 1")
c.eq("format mapping index","CSS:{0[CSS]:d};HTML:{0[HTML]:d}".format(table),"CSS:2;HTML:1")
c.eq("format mapping expansion","CSS:{CSS:d};HTML:{HTML:d}".format(**table),"CSS:2;HTML:1")
c.raises("format missing key",KeyError,lambda:"{missing}".format(**table))
c.raises("format auto/manual conflict",ValueError,lambda:"{} {0}".format(1))
c.raises("format wrong spec type",ValueError,lambda:"{:d}".format("1"))
input_runs=[]
for label,data,expected in[("text","蓝色天空网\n","请输入:记录: 蓝色天空网\n"),("blank","\n","请输入:记录: \n"),("EOF","","请输入:EOF\n")]:
r=subprocess.run([sys.executable,"-I","-B","-X","utf8",__file__,"--read-input"],input=data,capture_output=True,text=True,encoding="utf8",timeout=5)
c.eq("stdin exit "+label,r.returncode,0);c.eq("stdin output "+label,r.stdout,expected)
input_runs.append(dict(label=label,stdin=data,stdout=r.stdout,stderr=r.stderr))
work=P/"_runtime-work";work.mkdir(exist_ok=True);mode_contracts=[]
with tempfile.TemporaryDirectory(prefix="io-",dir=work)as folder:
root=Path(folder);assert root.resolve().is_relative_to(work.resolve())
for mode in["r","rb","r+","rb+","w","wb","w+","wb+","a","ab","a+","ab+"]:
path=root/("mode-"+mode.replace("+","plus")+".dat");path.write_bytes(b"abc")
binary="b"in mode;kwargs={}if binary else{"encoding":"utf8","newline":"\n"}
readable=mode.startswith("r")or"+"in mode;writable=mode[0]in"wa"or"+"in mode
with path.open(mode,**kwargs)as f:
position=f.tell();truncated=path.stat().st_size==0
c.eq("mode readable "+mode,f.readable(),readable);c.eq("mode writable "+mode,f.writable(),writable)
c.eq("mode initial position "+mode,position,3 if mode.startswith("a")else 0)
c.eq("mode truncate "+mode,truncated,mode.startswith("w"))
if readable:
f.seek(0);expected=(b""if mode.startswith("w")else b"abc")
c.eq("mode actual read "+mode,f.read(),expected if binary else expected.decode())
else:c.raises("mode cannot read "+mode,io.UnsupportedOperation,lambda:f.read())
if writable:
f.seek(0);c.eq("mode write length "+mode,f.write(b"Z"if binary else"Z"),1);f.flush()
else:c.raises("mode cannot write "+mode,io.UnsupportedOperation,lambda:f.write(b"Z"if binary else"Z"))
expected=b"abcZ"if mode.startswith("a")else b"Z"if mode.startswith("w")else b"Zbc"if writable else b"abc"
c.eq("mode final bytes "+mode,path.read_bytes(),expected)
missing=root/("new-"+mode.replace("+","plus")+".dat")
if mode.startswith("r"):
c.raises("mode missing fails "+mode,FileNotFoundError,lambda:missing.open(mode,**kwargs));created=False
else:
with missing.open(mode,**kwargs):pass
created=missing.exists();c.eq("mode creates missing "+mode,created,True)
mode_contracts.append(dict(mode=mode,readable=readable,writable=writable,creates=created,truncates=truncated,initial=position,final_bytes_hex=path.read_bytes().hex()))
exclusive=root/"exclusive.txt"
with exclusive.open("x",encoding="utf8")as f:f.write("owned")
c.raises("exclusive refuses overwrite",FileExistsError,lambda:exclusive.open("x",encoding="utf8"))
textfile=root/"text.txt"
with textfile.open("w",encoding="utf8",newline="\n")as f:
c.eq("text write counts characters",f.write("天\n"),2)
c.raises("text rejects bytes",TypeError,lambda:f.write(b"x"))
c.eq("UTF8 physical byte length",len(textfile.read_bytes()),4)
value = ("蓝天", 7)
tuple_file = root / "tuple.txt"
with tuple_file.open("w", encoding="utf-8", newline="\n") as stream:
c.raises("text rejects tuple", TypeError, lambda: stream.write(value))
c.eq("failed tuple write leaves position", stream.tell(), 0)
c.eq("converted tuple character count", stream.write(str(value)), 9)
c.eq("converted tuple close", stream.closed, True)
c.eq("converted tuple UTF-8 bytes", tuple_file.read_bytes(), "('蓝天', 7)".encode("utf-8"))
binaryfile=root/"binary.dat"
with binaryfile.open("wb")as f:
c.eq("binary write counts bytes",f.write("天\n".encode()),4)
c.raises("binary rejects str",TypeError,lambda:f.write("x"))
c.eq("text/binary explicit same encoded bytes",textfile.read_bytes(),binaryfile.read_bytes())
textfile.write_text("aa\n\nbbb",encoding="utf8",newline="\n")
with textfile.open(encoding="utf8")as f:
c.eq("read0 before EOF",f.read(0),"");c.eq("read1 character",f.read(1),"a")
c.eq("readnegative remaining",f.read(-1),"a\n\nbbb");c.eq("read EOF",f.read(),"")
with textfile.open(encoding="utf8")as f:
c.eq("readline first includes LF",f.readline(),"aa\n")
c.eq("blank line not EOF",f.readline(),"\n")
c.eq("last line without LF",f.readline(),"bbb");c.eq("readline EOF only now",f.readline(),"")
with textfile.open(encoding="utf8")as f:c.eq("readlines whole lines",f.readlines(),["aa\n","\n","bbb"])
with textfile.open(encoding="utf8")as f:c.eq("readlines hint not exact bytes",f.readlines(1),["aa\n"])
with textfile.open(encoding="utf8")as f:
c.eq("iteration first line",next(f),"aa\n");c.eq("manual read after iteration",f.read(),"\nbbb")
with textfile.open(encoding="utf8")as f:
next(f);c.raises("text iterator may disable tell",OSError,f.tell)
with textfile.open(encoding="utf8")as f:c.raises("read size not float",TypeError,lambda:f.read(1.5))
textfile.write_text("天\n空\n",encoding="utf8",newline="\n")
with textfile.open(encoding="utf8")as f:c.eq("unicode hint counts whole character lines",f.readlines(2),["天\n","空\n"])
binaryfile.write_bytes(b"0123456789abcdef")
with binaryfile.open("rb+")as f:
c.eq("binary seek absolute5",f.seek(5),5);c.eq("binary byte5",f.read(1),b"5")
c.eq("binary seek endminus3",f.seek(-3,2),13);c.eq("binary byte d",f.read(1),b"d")
c.eq("binary seek relative back1",f.seek(-1,1),13);c.eq("binary d repeated",f.read(1),b"d")
c.eq("file is not terminal",f.isatty(),False)
c.eq("truncate return size",f.truncate(3),3)
c.eq("truncate actual bytes",binaryfile.read_bytes(),b"012")
textfile.write_bytes("天空\n".encode())
with textfile.open(encoding="utf8")as f:
c.eq("unicode read one char",f.read(1),"天");cookie=f.tell()
c.eq("tell is not character count",cookie!=1,True)
rest=f.read();f.seek(cookie);c.eq("saved text cookie restores",f.read(),rest)
c.raises("text nonzero current offset unsupported",io.UnsupportedOperation,lambda:f.seek(1,1))
c.raises("text nonzero end offset unsupported",io.UnsupportedOperation,lambda:f.seek(-1,2))
c.eq("text seek0 current supported",type(f.seek(0,1)).__name__,"int")
c.eq("text seek0 end supported",type(f.seek(0,2)).__name__,"int")
c.eq("with closed actually",f.closed,True);c.eq("close again is allowed",f.close(),None)
c.raises("closed read fails",ValueError,f.read)
obj={"a":[1,2.0,3,4+6j],"b":("string","中文"),"c":None}
cycle=[1,2,3];cycle.append(cycle);dumpfile=root/"owned.pkl"
c.eq("fixed Python3.12 default protocol",pickle.DEFAULT_PROTOCOL,4)
c.eq("fixed Python3.12 highest protocol",pickle.HIGHEST_PROTOCOL,5)
with dumpfile.open("wb")as f:
pickle.dump(obj,f);pickle.dump(cycle,f,protocol=pickle.HIGHEST_PROTOCOL)
with dumpfile.open("rb")as f:
restored=pickle.load(f);recursion=pickle.load(f);c.raises("pickle after two objects EOF",EOFError,lambda:pickle.load(f))
c.eq("pickle dictionary actual roundtrip",restored,obj)
c.eq("pickle cycle prefix",recursion[:3],[1,2,3]);c.eq("pickle self identity preserved",recursion[-1]is recursion,True)
c.eq("pprint cycle readable","Recursion on list"in pprint.pformat(recursion),True)
explicit0=pickle.dumps(obj,protocol=0)
c.eq("explicit protocol0 first opcode",next(pickletools.genops(explicit0))[0].name,"MARK")
c.eq("explicit protocol0 roundtrip",pickle.loads(explicit0),obj)
binary_stream = io.BytesIO()
c.eq("protocol0 dump returns None", pickle.dump(obj, binary_stream, protocol=0), None)
c.eq("protocol0 stream produces bytes", binary_stream.getvalue(), explicit0)
binary_stream.seek(0)
c.eq("protocol0 stream recovers object", pickle.load(binary_stream), obj)
c.raises("pickle text stream refuses dump", TypeError, lambda: pickle.dump(obj, io.StringIO()))
c.raises("pickle text stream refuses load", TypeError, lambda: pickle.load(io.StringIO(explicit0.decode("latin1"))))
current=pickle.dumps(obj);c.eq("default pickle header protocol",next(pickletools.genops(current))[1],4)
c.raises("malformed own pickle rejected",pickle.UnpicklingError,lambda:pickle.loads(b"not pickle"))
c.eq("owned temporary directory cleaned",Path(folder).exists(),False)
c.finish("python3-inputoutput",mode_contracts=mode_contracts,stdin_runs=input_runs,text_cookie_observed=cookie,untrusted_or_source_pickle_loaded=False)
if __name__=="__main__":main()
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地 Python 环境
入口文件:projects/python-lab/python3-inputoutput.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python3-inputoutput.py,或下载右侧课程工程包。 - 确认本地已准备 本地 Python 环境。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip