GSubprocess(Gjs) Tips
# 最終更新日 2020.08.02
コマンド出力を得る
g_spawn_command_line_sync では文字列出力しか得ることができません python の subprocess と同様こちらはバイナリ出力も対応しています
#!/usr/bin/gjs const Gio = imports.gi.Gio; const GdkPixbuf = imports.gi.GdkPixbuf; // argv は array で渡す let sp = Gio.Subprocess.new(['ls', '-l'], Gio.SubprocessFlags.STDOUT_PIPE); let istream = sp.get_stdout_pipe(); let dstream = new Gio.DataInputStream({base_stream:istream}); for (;;) { let [s, l] = dstream.read_line_utf8(null); if (s == null) break; print(s); } // JPEG 画像のバイナリを取得し PNG 変換の例 sp = Gio.Subprocess.new(['cat', 'SUZUKI刀.jpg'], Gio.SubprocessFlags.STDOUT_PIPE); istream = sp.get_stdout_pipe(); let p = GdkPixbuf.Pixbuf.new_from_stream(istream, null); p.savev('超カッケーバイク.png', 'png', ['compression'], ['9']);
非同期でコマンドを実行
コマンド結果より __done__ のほうが先に表示されるはず
#!/usr/bin/gjs const Gio = imports.gi.Gio; let subprocess = Gio.Subprocess.new(['ls', '-la'], Gio.SubprocessFlags.STDIN_PIPE); let buf = new Uint8Array(0); subprocess.communicate_async(buf, null, (source_object, res)=> { let istream = source_object.get_stdout_pipe(); let dstream = new Gio.DataInputStream({base_stream:istream}); for (;;) { let [s, l] = dstream.read_line_utf8(null); if (s == null) break; print(s); } }); print('__done__');
Copyright(C) sasakima-nao All rights reserved 2002 --- 2023.