以前下記で Seed, Python で Gio による読み書きをやったのを Gjs にしてみた。
Gio Streaming I/O @ Seed and PyGI | PaePoi
GCancellable 等を指定(null でいい)しないといけなかった。
他色々と Seed より Python に似ていて困惑。
/*
Gjs Streaming I/O File Read and Write Sample
*/
const Gio = imports.gi.Gio;
const Format = imports.format;
String.prototype.format = Format.format;
let filename = "test_gjs.txt";
const lines = "Japan\n\n日本語";
// Write
let f = Gio.file_new_for_path(filename);
let fstream = f.replace(null, false, Gio.FileCreateFlags.NONE, null);
try {
// Error, This is no Exception.
// let dstream = new Gio.DataOutputStream(fstream);
// g_output_stream_write: assertion 'G_IS_OUTPUT_STREAM (stream)' failed
let dstream = new Gio.DataOutputStream({base_stream:fstream});
dstream.put_string(lines, null);
} catch (e) {
// Without meaning
log("*** ERROR WRITE: " + e.message);
}
fstream.close(null);
// Read
f = Gio.file_new_for_path(filename);
fstream = f.read(null);
// Same as above
let dstream = new Gio.DataInputStream({base_stream:fstream});
while (1) {
let [text, len] = dstream.read_line_utf8(null);
if (text == null) break;
print("%s(%d)".format(text, len));
// or print(text + "(" + len + ")");
}
fstream.close(null);
/* output
Japan(5)
(0)
日本語(9)
*/
DataOutputStream 等の引数は json で指定しないと認識してくれない。
現時点では理由が解らない、GOutputStream のサブクラスと認識できないのか?
とにかく Error で困ったら json 指定にすればなんとかなるっぽい。
しかも GError 引数なのに例外にならず普通にエラー。
try ブロックを書いたけど無意味だった、これはちと困る。
おまけで let 変数のスコープは try ブロック内でも有効だと解った。
Python と同様にするには var を利用、注意しよう。
// var is OK
let f = Gio.file_new_for_path("a.txt");
try {
// var fstream = f.replace(null, false, Gio.FileCreateFlags.NONE, null);
let fstream = f.replace(null, false, Gio.FileCreateFlags.NONE, null);
} catch (e) {
//
}
fstream.close(null); // ReferenceError
# Python is OK
f = Gio.file_new_for_path(filename)
try:
fstream = f.replace("", False, Gio.FileCreateFlags.NONE, None)
except Exception as e:
pass
fstream.close(None)
Seed にある c_new という意味不明な指定が無いのはちょっぴり嬉しいね。
それ以外は全部 Gjs のほうが面倒臭いけど。
戻り値が Python 同様に 2 つ以上である場合がある。
Python はタプルなんだけど、タプルが無い言語でもこの手があったか。
まあどちらも引数に渡された変数の値を変更できない言語だし。
どうも PyGObject の手段を参考に作っているような気がする。
いや逆かも、というか GLib 側の意向でこうなったのかな?
とにかく Python 屋なら Seed より Gjs のほうがなじみやすいという結論で。