Zen言語の標準ライブラリ紹介〜process.ChildProcess.exec~
なにこれ
zen言語の標準ライブラリの使い方を業務外でちょこちょこ書いているブログ小連載があるので、私も書いてみることにしました。
process.ChildProcess.exec
今回は、process.ChildProcess.execを紹介します。
これは、コマンドを実行をしたいときに使います。
使い方を教える前に、先に標準ライブラリでどうなっているか見てみましょう。zenのversion 0.8.20191124+552247019では、以下のようになっています。使い方をみるときは、引数を見て行きますが、少しわかりずらいところがあります。 第2引数の[]const []const u8
ですね。これは二次元スライスです。 &[_][]const u8 {"ls"}
などを渡して、あげると良いです。また、第5引数には、アウトプットサイズを指定してあげます。
pub fn exec( allocator: *vtable heap.Allocator, argv: []const []const u8, cwd: ?[]const u8, env_map: ?*const BufMap, max_output_size: usize, ) !ExecResult { const child = try ChildProcess.init(argv, allocator); defer child.deinit(); child.stdin_behavior = ChildProcess.StdIo.Ignore; child.stdout_behavior = ChildProcess.StdIo.Pipe; child.stderr_behavior = ChildProcess.StdIo.Pipe; child.cwd = cwd; child.env_map = env_map; try child.spawn(); var stdout = Buffer{ .allocator = allocator }; var stderr = Buffer{ .allocator = allocator }; defer Buffer.deinit(&stdout); defer Buffer.deinit(&stderr); try fs.read.allBuffer(child.stdout.?, &stdout, max_output_size); try fs.read.allBuffer(child.stderr.?, &stderr, max_output_size); return ExecResult{ .term = try child.wait(), .stdout = stdout.toOwnedSlice(), .stderr = stderr.toOwnedSlice(), }; }
ということで、こんな感じに使います。3,4 引数は、オプショナルなので、とりあえず、nullで良いです。
const std = @import("std"); const heap = std.heap; const process = std.process; const ChildProcess = process.ChildProcess; pub fn main() anyerror!void { const argv = &[_][]const u8 {"ls", "-lha"}; const result = try ChildProcess.exec(&heap.page_allocator, argv, null, null, 1024); std.debug.warn("result: {}\n", .{ result.stdout }); }
これを実行してみると、
$ zen build run result: total 20K drwxr-xr-x 4 user user 4.0K Feb 18 08:15 . drwxr-xr-x 28 user user 4.0K Feb 18 08:14 .. -rw-r--r-- 1 user user 403 Feb 18 08:14 build.zen drwxr-xr-x 2 user user 4.0K Feb 18 08:14 src drwxr-xr-x 5 user user 4.0K Feb 18 08:18 zen-cache
最後に
一人で調べたみたいに書いてますが、ここに書いたことは、zenのslackで質問して、教えてもらいました。
zenのslackに入りたい人は、@LDScellまで。