"""蓝色天空网 mbsky.com — 自有多文件模块、包及解释器观察。"""
from pathlib import Path
import sys,io,contextlib,subprocess,json,importlib,math,os,random,datetime,re,itertools,functools
from collections import deque,defaultdict
P=Path(__file__).resolve().parent;sys.path.insert(0,str(P))
from mbsky_pychecks import Checks
def main():
c=Checks()
import mbsky_support
out=io.StringIO()
with contextlib.redirect_stdout(out):result=mbsky_support.print_greeting("学习者")
c.eq("support real output",out.getvalue(),"蓝色天空网欢迎 学习者\n");c.eq("support returns None",result,None)
import mbsky_fibonacci as fibo
c.eq("fibonacci below100",fibo.below(100),[1,1,2,3,5,8,13,21,34,55,89])
c.eq("fibonacci below500",fibo.below(500),[1,1,2,3,5,8,13,21,34,55,89,144,233,377])
c.eq("fibonacci below1000 last",fibo.below(1000)[-1],987)
c.eq("fibonacci empty boundary",fibo.below(1),[])
out=io.StringIO()
with contextlib.redirect_stdout(out):fibo.show(10)
c.eq("module prints fibonacci",out.getvalue(),"1 1 2 3 5 8\n")
c.eq("module own name",fibo.__name__,"mbsky_fibonacci")
alias=fibo.below;c.eq("function alias same object",alias is fibo.below,True)
namespace={};exec("from mbsky_fibonacci import below, show",namespace)
c.eq("from import only named bindings","below"in namespace and"show"in namespace and"mbsky_fibonacci"not in namespace,True)
c.eq("module still loaded",sys.modules["mbsky_fibonacci"]is fibo,True)
namespace={};exec("import mbsky_fibonacci as numbers\nfrom math import sqrt as root",namespace)
c.eq("module alias object",namespace["numbers"]is fibo,True);c.eq("function alias call",namespace["root"](9),3.0)
import mbsky_cache_probe
c.eq("first module initialization",mbsky_cache_probe.LOADS,1)
second=importlib.import_module("mbsky_cache_probe")
c.eq("ordinary import uses same object",second is mbsky_cache_probe,True);c.eq("ordinary import does not rerun",second.LOADS,1)
importlib.reload(second);c.eq("explicit reload reruns",second.LOADS,2)
c.eq("sys is builtin origin",sys.__spec__.origin,"built-in")
c.eq("sys has no source filename",hasattr(sys,"__file__"),False)
c.eq("sys in builtin module names","sys"in sys.builtin_module_names,True)
argv_runs=[]
for isolated,flags in [(False,["-E","-s","-B"]),(True,["-I","-B"])]:
r=subprocess.run([sys.executable,*flags,"-X","utf8",str(P/"mbsky_arg_probe.py"),"参数1","参数2"],capture_output=True,text=True,encoding="utf8",timeout=6)
c.eq("argv child status "+str(isolated),r.returncode,0);d=json.loads(r.stdout)
c.eq("actual unicode argv "+str(isolated),d["args"],["参数1","参数2"])
c.eq("script directory startup rule "+str(isolated),d["scriptdir_first"],not isolated)
c.eq("actual isolation flag "+str(isolated),d["isolated"],int(isolated));argv_runs.append(d)
sys.path[:0]=[str(P/"search_b"),str(P/"search_a")]
import mbsky_search_target
c.eq("owned path ordering",mbsky_search_target.VALUE,"second owned directory")
c.eq("noninteractive ps1 not guaranteed",hasattr(sys,"ps1"),False)
interactive=subprocess.run([sys.executable,"-I","-B","-X","utf8","-i","-c","import sys;sys.ps1='SKY> ';sys.ps2='MORE> '"],input='print("mbsky.com")\nexit()\n',capture_output=True,text=True,encoding="utf8",timeout=6)
c.eq("interactive child exits",interactive.returncode,0);c.eq("interactive actual stdout",interactive.stdout,"mbsky.com\n")
c.eq("interactive custom prompt displayed","SKY> "in interactive.stderr,True)
c.eq("dir includes definitions","below"in dir(fibo)and"__name__"in dir(fibo),True)
marker=1;c.eq("dir local after assignment","marker"in dir(),True);del marker;c.eq("dir local after delete","marker"in dir(),False)
class Discover:
def __dir__(self):return ["custom"]
c.eq("dir can be customized",dir(Discover()),["custom"])
c.eq("math sqrt",math.sqrt(9),3.0);c.eq("math trigonometric",math.sin(0),0.0)
c.eq("os path operation",os.path.basename(str(P/"note.txt")),"note.txt")
c.eq("random local repeat",random.Random(42).random(),random.Random(42).random())
c.eq("datetime ISO",datetime.date(2024,2,29).isoformat(),"2024-02-29")
data={"brand":"蓝色天空网","hours":[1,2]}
c.eq("json round trip",json.loads(json.dumps(data,ensure_ascii=False)),data)
c.eq("regex whole match",re.fullmatch(r"mbsky[.]com","mbsky.com")is not None,True)
q=deque(["HTML","CSS"]);c.eq("collections dequeue",q.popleft(),"HTML")
grouped=defaultdict(list);grouped["CSS"].append("learn");c.eq("collections default factory",dict(grouped),{"CSS":["learn"]})
c.eq("itertools finite slice",list(itertools.islice(itertools.count(1),3)),[1,2,3])
c.eq("functools reduction",functools.reduce(lambda a,b:a*b,[2,3,4]),24)
computed=[]
@functools.lru_cache(maxsize=2)
def square(value):computed.append(value);return value*value
c.eq("functools cache miss result",square(4),16)
c.eq("functools cache hit result",square(4),16)
c.eq("functools cache underlying call",computed,[4])
c.eq("functools cache hit miss statistics",(square.cache_info().hits,square.cache_info().misses),(1,1))
import mbsky_audio.effects.echo
c.eq("full package path call",mbsky_audio.effects.echo.echofilter([1,2]),[1.0,2.5,1.0])
from mbsky_audio.effects import echo
c.eq("submodule import same",echo is mbsky_audio.effects.echo,True)
from mbsky_audio.effects.echo import echofilter
c.eq("function import same",echofilter is echo.echofilter,True)
from mbsky_audio.effects import lesson
c.eq("three relative import forms",lesson.result(),(("wav","aiff","au"),[1.0,2.5,1.0],[2,4]))
exported={};exec("from mbsky_audio.effects import *",exported)
c.eq("package all exact names",sorted(k for k in exported if not k.startswith("__")),["echo","reverse","surround"])
c.eq("all imports reverse module",exported["reverse"].reverse([1,2]),[2,1])
c.eq("all imports surround module",exported["surround"].stereo([1,2]),[(1,1),(2,2)])
import mbsky_plain
c.eq("unlisted submodule not auto loaded","mbsky_plain.hidden_part"in sys.modules,False)
exported={};exec("from mbsky_plain import *",exported)
c.eq("without all no filesystem scan",sorted(k for k in exported if not k.startswith("__")),["LABEL"])
import mbsky_plain.hidden_part
exported={};exec("from mbsky_plain import *",exported)
c.eq("already bound public submodule exported","hidden_part"in exported,True)
exported={};exec("from mbsky_exports import *",exported)
c.eq("explicit all includes underscore",sorted(k for k in exported if not k.startswith("__")),["_explicit","public"])
c.eq("explicit all excludes ordinary name","hidden"not in exported,True)
sys.path[:0]=[str(P/"namespace_a"),str(P/"namespace_b")]
import mbsky_sharedspace
from mbsky_sharedspace import left,right
c.eq("namespace package has no init origin",mbsky_sharedspace.__spec__.origin,None)
c.eq("namespace package two locations",len(list(mbsky_sharedspace.__path__)),2)
c.eq("namespace portions both work",(left.VALUE,right.VALUE),("left namespace portion","right namespace portion"))
c.raises("missing package member ImportError",ImportError,lambda:exec("from mbsky_plain import no_such_member",{}))
c.finish("python3-module",argv_runs=argv_runs,interactive_prompts_in_owned_child=True,audio_namespace_only_numeric_teaching=True,source_archive_scripts_executed=False)
if __name__=="__main__":main()
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地 Python 环境
入口文件:projects/python-lab/python3-module.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python3-module.py,或下载右侧课程工程包。 - 确认本地已准备 本地 Python 环境。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip