DefineOutputStreamMethod["name",{"fname1"function1,"fname2"function2,… }]
指定された名前のカスタム出力ストリームメソッドを定義し,出力ストリームを開いたりこれに書き込んだりするためにWolfram言語がストリーム関数を呼び出すことを許す.
DefineOutputStreamMethod
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によって使われる.
- With 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]として呼び出す.関数n 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]]内部状態がなければ,デフォルトのストリーム位置は常に-1になる:
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), DefineOutputStreamMethod, Wolfram言語関数, https://reference.wolfram.com/language/ref/DefineOutputStreamMethod.html.
CMS
Wolfram Language. 2012. "DefineOutputStreamMethod." Wolfram Language & System Documentation Center. Wolfram Research. https://reference.wolfram.com/language/ref/DefineOutputStreamMethod.html.
APA
Wolfram Language. (2012). DefineOutputStreamMethod. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/DefineOutputStreamMethod.html
BibTeX
@misc{reference.wolfram_2026_defineoutputstreammethod, author="Wolfram Research", title="{DefineOutputStreamMethod}", year="2012", howpublished="\url{https://reference.wolfram.com/language/ref/DefineOutputStreamMethod.html}", note=[Accessed: 13-September-2026]}
BibLaTeX
@online{reference.wolfram_2026_defineoutputstreammethod, organization={Wolfram Research}, title={DefineOutputStreamMethod}, year={2012}, url={https://reference.wolfram.com/language/ref/DefineOutputStreamMethod.html}, note=[Accessed: 13-September-2026]}