DefineOutputStreamMethod["name",{"fname1"function1,"fname2"function2,… }]
定义一个具有指定名称的自定义输出流方法,使得 Wolfram 语言可以调用流函数,用于打开和读取输出流.
DefineOutputStreamMetho
DefineOutputStreamMethod["name",{"fname1"function1,"fname2"function2,… }]
定义一个具有指定名称的自定义输出流方法,使得 Wolfram 语言可以调用流函数,用于打开和读取输出流.
更多信息
- 输出流方法是创建 OutputStream 对象的不同方式. DefineOutputStreamMethod 允许将新的输出流方法添加到预定义列表中.
- 一个输出流方法可以提供一种方式,将流写入到新的输出目标,对输出流进行过滤(例如加密或压缩),在写入时执行副作用,或者组合实现这些功能.
- 可以提供下列输出流函数:
-
"NameTestFunction" 给定名称的流是否能被打开 "ConstructorFunction" 当打开一个新的流时调用 "CloseFunction" 关闭流并且释放它的资源 "WriteFunction" 对流写入字节 "FlushFunction" 确保在内存中缓存的字节写入流中 "StreamPositionFunction" 输入读取的流中的当前点 "OptionChangesFunction" 修改由 Options[stream] 返回的选项 - 函数列表中必须包含 "ConstructorFunction". 其他函数如果未提供,则具有默认行为. 虽然不强制要求,但如果不包含 "WriteFunction",流将实际上忽略写入它的所有输出,因此通常应包含它.
- 使用流方法打开的每个 OutputStream 都有一个当前状态. 初始状态表达式由 "ConstructorFunction" 返回. 其他函数将当前状态视为参数,并且返回新的状态值. 这个状态表达式是流方法可以存储信息的地方,例如网络连接、已写入的字节数以及流方法函数所需的其他信息.
- 如果返回新状态值的函数没有提供,那么默认定义返回未修改的给定状态.
- 如果 Method 选项使用了注册的输出流方法名称,或者 MethodAutomatic,并且该输出流的 "NameTestFunction" 对输出流名称返回 True,则 OpenWrite 或 OpenAppend 会使用该输出流方法.
- 当 MethodAutomatic 时,OpenWrite["name"] 和 OpenAppend["name"] 调用 "NameTestFunction"f 执行 f["name"],若 f 返回 True,则使用该输出流方法构造流.
- 如果没有提供 "NameTestFunction",默认的行为是返回 False.
- 当 OpenWrite 或 OpenAppend 打开一个输出流时,它们会调用 "ConstructorFunction"f 执行 f[name,isAppend,caller,opts],其中 name 是流名称(文件路径、URL 或其他流标识符),而 isAppend 对于 OpenAppend 为 True,对于 OpenWrite 为 False. caller 可以是 OpenWrite 或 OpenAppend,可用于发出消息. opts 参数是选项规则. 函数 f 应返回一个列表 {success,state},其中 success 在构造函数成功打开流时为 True,而 state 是流状态的初始值.
- 当 Method{"method","name"value,...} 时,位于 "method" 之后的规则会被包含在传递给 "ConstructorFunction" 的 opts 规则中. 这允许调用者向输出流方法传递设置.
- Close[stream] 调用 "CloseFunction"f 执行 f[state]. 这是将在输出流上调用的最后一个函数,因此它应执行所有必要的资源清理.
- 如果未提供 "CloseFunction",默认实现什么也不做.
- 诸如 Write 和 WriteString 这样的流写入函数会调用 "WriteFunction"f 执行 f[state,{byte1,...}]. 函数 f 应返回一个列表 {byteCount,state}. 其中 byteCount 应指示实际写入的字节数. 返回的 state 将作为该流新的当前状态表达式传递给其他函数.
- 如果未提供 "WriteFunction",默认实现返回字节计数 0,并传递未修改的给定状态.
- 诸如 Write 和 WriteString 这样的流写入函数,可能会调用 "FlushFunction"f 执行 f[state],以确保输出字节从内存缓冲区传输到其目标位置. 函数 f 应返回一个列表 {Null,state},其中 state 是新的流状态表达式.
- 如果 "WriteFunction" 总是在返回之前刷新其缓冲区,或者不使用缓冲区,则不需要提供 "FlushFunction".
- StreamPosition 将调用 "StreamPositionFunction"f 执行 f[state]. 函数 f 应返回一个列表 {nbytes,state},其中 nbytes 是写入流的字节数,而 state 是新的流状态表达式(可以不变).
- "OptionChangesFunction" 用于让流方法更改 Options[stream,Method] 返回的值,适用于选项包含秘密(如密码)的情况.
- Options[stream] 将调用 "OptionChangesFunction"f 执行 f[state,opts]. 函数 f 应返回一个列表 {newopts,state},其中 newopts 将用作由 Options 返回的 Method 选项设置.
- 如果已存在同名的输出流方法,DefineOutputStreamMethod 将失败.
- 可以使用 RemoveOutputStreamMethod 移除输出流方法.
范例
打开所有单元 关闭所有单元基本范例 (1)
DefineOutputStreamMethod["DatedPrint", {
"ConstructorFunction" -> ({True, Null}&),
"WriteFunction" -> ({Length[#2],
If[#2 =!= ToCharacterCode["
"], Print[DateString[], "
", FromCharacterCode[#2]]
]}&)
}]str = OpenWrite["dateprinter", Method -> "DatedPrint"]Write[str, "hello, world"]
Write[str, {a ^ 2, 1 + b ^ 2}]Close[str]范围 (6)
定义一种使用 "NameTestFunction" 的输出流方法,打开名称以 "dateprinter:" 开头的流:
DefineOutputStreamMethod["DatePrinter", {
"NameTestFunction" -> StringStartsQ["dateprinter:"],
"ConstructorFunction" -> ({True, Null}&),
"WriteFunction" -> ({Length[#2],
If[#2 =!= ToCharacterCode["
"], Print[DateString[], "
", FromCharacterCode[#2]]
]}&)
}]仅基于名称(无需 Method 选项)使用此方法打开流:
strm = OpenWrite["dateprinter:"]Write[strm, "hello, world"]
Write[strm, a ^ 2, {-π, π / 2}]Close[strm]定义一个写入文件的输出流方法,同时保持一个校验和,在流关闭时打印:
DefineOutputStreamMethod[
"FileChecksum",
{
"ConstructorFunction" ->
Function[{name, append, caller, opts},
{True, <|"Stream" -> OpenWrite[name, BinaryFormat -> True], "FileName" -> name, "ByteCount" -> 0, "Checksum" -> 0|>}
],
"CloseFunction" -> Function[state, Print[KeyDrop[state, "Stream"]];Close[state["Stream"]]],
"WriteFunction" ->
Function[{state, bytes},
Module[{newstate = state, count = Length[bytes]},
BinaryWrite[state["Stream"], bytes];
newstate["ByteCount"] += count;
newstate["Checksum"] += Total[bytes];
{count, newstate}
]
],
"StreamPositionFunction" -> Function[state, {state["ByteCount"], state}]
}
]str = OpenWrite["file.log", FormatType -> OutputForm, Method -> "FileChecksum"]Write[str, DateString[], " ", MemoryInUse[]]
Write[str, DateString[], " ", MemoryInUse[]]StreamPosition[str]Close[str]FilePrint["file.log"]定义一种输出流方法,通过将每个字节“旋转”一个在 Method 选项中传递给构造函数的数字来模糊其文件:
DefineOutputStreamMethod[
"RotateObscuredFile",
{
"ConstructorFunction" ->
Function[{name, append, caller, opts},
{True, <|"Stream" -> OpenWrite[name, BinaryFormat -> True], "ByteCount" -> 0, "Rotate" -> With[{n = Lookup[opts, "Rotate", 0]}, Mod[# + n, 256]&]|>}
],
"CloseFunction" -> Function[state, Close[state["Stream"]]],
"WriteFunction" ->
Function[{state, bytes},
Module[{newstate = state, count = Length[bytes]},
BinaryWrite[state["Stream"], Map[state["Rotate"], bytes]];
newstate["ByteCount"] += count;
{count, newstate}
]
]
}
]strm = OpenWrite["file.txt", Method -> "RotateObscuredFile"]检查打开流的 Method 选项:
Options[strm, Method]Write[strm, "The quick brown fox jumped."]Close[strm]FilePrint["file.txt"]strm = OpenWrite["file.txt", Method -> {"RotateObscuredFile", "Rotate" -> 2}]检查打开流的 Method 选项:
Options[strm, Method]Write[strm, "The quick brown fox jumped."]Close[strm]FilePrint["file.txt"]定义一种输出流方法,通过将每个字节“旋转”一个在 Method 选项中传递给构造函数的数字来模糊其文件,但使用 "OptionChangesFunction" 隐藏流选项中的参数:
DefineOutputStreamMethod[
"ObscureFile",
{
"ConstructorFunction" ->
Function[{name, append, caller, opts},
{True, <|"Stream" -> OpenWrite[name, BinaryFormat -> True], "ByteCount" -> 0, "Rotate" -> With[{n = Lookup[opts, "Rotate", 0]}, Mod[# + n, 256]&]|>}
],
"OptionChangesFunction" -> Function[{state, options}, {FilterRules[options, Except["Rotate"]], state}],
"CloseFunction" -> Function[state, Close[state["Stream"]]],
"WriteFunction" ->
Function[{state, bytes},
Module[{newstate = state, count = Length[bytes]},
BinaryWrite[state["Stream"], Map[state["Rotate"], bytes]];
newstate["ByteCount"] += count;
{count, newstate}
]
]
}
]strm = OpenWrite["file.txt", Method -> {"ObscureFile", "Rotate" -> 2}]检查打开流的 Method 选项,显示敏感的 "Rotate" 值未显示:
Options[strm, Method]Write[strm, "The quick brown fox jumped."]Close[strm]FilePrint["file.txt"]DefineOutputStreamMethod["NullStream", {"ConstructorFunction" -> ({True, Null}&)}]strm = OpenWrite["test", Method -> "NullStream"]Write[strm, RandomInteger[{0, 255}, 10 ^ 7]]StreamPosition[strm]Close[strm]DefineOutputStreamMethod["FailingStream", {"ConstructorFunction" -> ({False, Null}&)}]strm = OpenWrite["test", Method -> "FailingStream"]巧妙范例 (1)
定义一种输出流方法,从流数据创建 Image 并在流关闭时将其传递给一个函数:
DefineOutputStreamMethod[
"ImageWriter",
{
"ConstructorFunction" ->
Function[{n, a, hd, opts},
With[{rcvr = Lookup[opts, "Receiver"]},
{!MissingQ[rcvr], <|"Bytes" -> <||>, "Count" -> 0, "Receiver" -> rcvr|>}
]
],
"WriteFunction" ->
Function[{state0, bytes},
Module[{state = state0},
state["Bytes"][Length[state["Bytes"]] + 1] = bytes;
{Length[bytes], state}
]
],
"CloseFunction" ->
Function[state,
Module[{bytes, side},
bytes = Flatten[Values[state["Bytes"]]];
side = Ceiling[Sqrt[Length[bytes]]];
(* call the receiver hook and pass it the Image *)
state["Receiver"][Image[ArrayReshape[bytes, {side, side}, 0], "Byte"]]
]
]
}
]打开一个流,传递一个函数,该函数将最终的图像分配给一个变量:
strm = OpenWrite["test", Method -> {"ImageWriter", "Receiver" -> Function[img, testimg = img]}]Write[strm, "The quick brown fox jumped over the lazy dogs."]
Write[strm, m x + b, Range[10]]Close[strm]计算在 Method 选项中传入的函数所赋值的变量:
testimgFromCharacterCode[Map[Round[256 * #]&, Flatten[ImageData[testimg]]]]技术笔记
-
▪
- 流式方法
文本
Wolfram Research (2012),DefineOutputStreamMetho,Wolfram 语言函数,https://reference.wolfram.com/language/ref/DefineOutputStreamMethod.html.
CMS
Wolfram 语言. 2012. "DefineOutputStreamMetho." Wolfram 语言与系统参考资料中心. Wolfram Research. https://reference.wolfram.com/language/ref/DefineOutputStreamMethod.html.
APA
Wolfram 语言. (2012). DefineOutputStreamMetho. Wolfram 语言与系统参考资料中心. 追溯自 https://reference.wolfram.com/language/ref/DefineOutputStreamMethod.html 年
BibTeX
@misc{reference.wolfram_2026_defineoutputstreammetho, author="Wolfram Research", title="{DefineOutputStreamMetho}", year="2012", howpublished="\url{https://reference.wolfram.com/language/ref/DefineOutputStreamMethod.html}", note=[Accessed: 15-September-2026]}
BibLaTeX
@online{reference.wolfram_2026_defineoutputstreammetho, organization={Wolfram Research}, title={DefineOutputStreamMetho}, year={2012}, url={https://reference.wolfram.com/language/ref/DefineOutputStreamMethod.html}, note=[Accessed: 15-September-2026]}