仓库源文

交互环境

常用命令调用无需()

Direct support for REPL-specific commands like help, exit, and quit, without the need to call them as functions.

这点木兰也具备:

% 木兰
木兰向您问好
更多信息请说'你好'
> 你好
    详情: 列出内置功能
    再会: 结束对话
    你好: 显示这段
> 再会
%

整段代码黏贴

“Paste mode” with F3 that makes pasting larger blocks of code easier (press F3 again to return to the regular prompt).

经测试 Python 3.13 的交互环境下可粘贴整段:

>>> import sys, cmd; from random import randrange
... 
... class 猜数字(cmd.Cmd):
...     intro, prompt = "我想了个 100 之内的数,猜猜是几?", '请猜吧: '
...     想的 = randrange(1000) // 10
... 
...     def default(self, 行):
...         try:
...             数 = int(行)
...         except ValueError as 例外:
...             print(行 + " 不是数,请再试")
...             return
...         self.比较(数)
... 
...     def 比较(self, 数):
...         if 数 == self.想的:
...             print("中了!")
...             sys.exit()
...         print("太大了!" if 数 > self.想的 else "太小了!")
... 
... 猜数字().cmdloop()
... 
我想了个 100 之内的数,猜猜是几?
。。。。

Python 3.12 按行解析会报错。

木兰交互环境也支持黏贴多行代码:

> using sys, cmd
> using randrange in random
> 
> type 猜数字 : cmd.Cmd {
>>    {
>>     intro, prompt = tuple('我想了个 100 之内的数,猜猜是几?', '请猜吧: ')
>>     想的 = randrange(1000) / 10
>>   }
>> 
>>   func $default(行) {
>>     try {
>>       数 = int(行)
>>     }
>>     catch 例外 : ValueError {
>>       println(行 + ' 不是数,请再试')
>>       return
>>     }
>>     $比较(数)
>>   }
>> 
>>   func $比较(数) {
>>     if (数 == $想的) {
>>       println('中了!')
>>       sys.exit()
>>     }
>>     println((数 > $想的) ? '太大了!' : '太小了!')
>>   }
>> }
> 猜数字().cmdloop()
我想了个 100 之内的数,猜猜是几?
。。。。

报错信息

文件名与标准库重名

% python random.py 
Traceback (most recent call last):
  File "【...】/random.py", line 1, in <module>
    import random
  File "【...】/random.py", line 3, in <module>
    print(random.randint(5))
          ^^^^^^^^^^^^^^
AttributeError: module 'random' has no attribute 'randint' (consider renaming '【...】/random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module)

个人认为,AttributeError: module 'random' has no attribute 'randint' 实际上包含了“import的是当前模块而非标准库”这一隐含信息,而对定位问题并无帮助,大可以直接去掉而采用括号内反馈信息。

木兰当下并无针对此引用场景的特定报错,using random 会加载木兰模块本身,于是按一般递归报错。

% 木兰 random.ul
 😰 递归过深。请确认: 1、的确需要递归 2、递归的收敛正确
 调用层级如下
。。。。
见第1行:using random
“【...】/木兰/环境.py”第85行:exec(可执行码, 模块.__dict__)
“【...】/木兰/环境.py”第173行:return 加载木兰模块(名称, 全局, 源自, 目录相对层次)
“【...】/木兰/环境.py”第177行:raise 例外
。。。。【递归循环】