From 68c96deb36e33db4b54977a63fb331978c300922 Mon Sep 17 00:00:00 2001 From: Jianhui Zhao Date: Wed, 25 Dec 2024 17:51:34 +0800 Subject: [PATCH] feat(sys): Add a method `sh` to run shell cmd simply Signed-off-by: Jianhui Zhao --- examples/shell.lua | 31 +++++++++++++++++++++++++++++++ sys.lua | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100755 examples/shell.lua diff --git a/examples/shell.lua b/examples/shell.lua new file mode 100755 index 0000000..650f2be --- /dev/null +++ b/examples/shell.lua @@ -0,0 +1,31 @@ +#!/usr/bin/env eco + +local sys = require 'eco.sys' + +local stdout, stderr, err = sys.sh('date', '-u') +print('stdout:', stdout) +print('stderr:', stderr) + +if err then + print('err:', err) +end + +print('-----------------') + +stdout, stderr, err = sys.sh('date -u >&2') +print('stdout:', stdout) +print('stderr:', stderr) + +if err then + print('err:', err) +end + +print('-----------------') + +stdout, stderr, err = sys.sh('sleep 2', 1) +print('stdout:', stdout) +print('stderr:', stderr) + +if err then + print('err:', err) +end diff --git a/sys.lua b/sys.lua index 6ce7d2e..a68b417 100644 --- a/sys.lua +++ b/sys.lua @@ -58,6 +58,40 @@ function M.exec(...) }, exec_metatable) end +-- stdout, stderr, err = sys.sh(cmd, timeout) +function M.sh(cmd, timeout) + assert(type(cmd) == 'string' or type(cmd) == 'table', 'cmd must be a string or table') + + if type(cmd) == 'string' then + cmd = { '/bin/sh', '-c', cmd } + end + + local p, err = M.exec(table.unpack(cmd)) + if not p then + return nil, nil, err + end + + local stdout, stderr + + timeout = timeout or 30 + + stdout, err = p:read_stdout('*a', timeout) + if not stdout then + p:close() + return nil, nil, err + end + + stderr, err = p:read_stderr('*a', timeout) + if not stderr then + p:close() + return stdout, nil, err + end + + p:close() + + return stdout, stderr +end + function M.signal(sig, cb, ...) local w = eco.watcher(eco.SIGNAL, sig)