如何启动子进程(通过 shell)并在子进程返回之前(之前)读取其输出?
我使用以下命令通过 Mac 终端启动 Google Chrome:
/Applications/Google\Chrome.app/Contents/MacOS/Google\Chrome --remote-debugging-port=9222 --no-first-run --no-default-browser-check --user-data- dir=$(mktemp -d -t 'chrome-remote_data_dir')
这运作良好,但直到我完成浏览器之后,该过程才会结束/返回。然而,一旦启动,它就会在控制台上打印以下内容:
“DevTools 监听 ws://127.0.0.1:9222/devtools/browser/d43342be-66bc-41d4-b591-a7ee22d1c528”
我需要刮掉它。我可以使用以下命令在 Deno(v.1.36.3)中成功启动它:
const myCMD = `/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome`;
const p = Deno.run({
cmd: [
myCMD,
"--remote-debugging-port=9222",
"--no-first-run",
"--no-default-browser-check",
"--user-data-dir=$(mktemp -d -t 'chrome-remote_data_dir')",
],
stdout: "piped",
stderr: "piped",
stdin: "piped",
});
await p.stdin.write(new TextEncoder().encode("Coming from stdin\n"));
await p.status();
但我无法读取所需的值,因为该过程未完成,因此输出永远不会返回。有没有办法在子进程返回之前读取子进程写入控制台的内容?
仅供引用...我使用以下文章作为引用:https://medium.com/deno-the-complete-reference/run-shell-commands-in-deno-26c3e9b72e03
最佳答案
您需要读取p.stdout
和p.stderr
,它们都是FsFile
的实例。因此您可以使用 .read
访问 ReadableStream
或者使用FsFile
.read
方法
const myCMD = `/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome`;
const p = Deno.run({
cmd: [
myCMD,
"--remote-debugging-port=9222",
"--no-first-run",
"--no-default-browser-check",
"--user-data-dir=$(mktemp -d -t 'chrome-remote_data_dir')",
],
stdout: "piped",
stderr: "piped",
stdin: "piped",
});
(async() => {
for await(const chunk of p.stdout.readable) {
console.log(chunk, new TextDecoder().decode(chunk))
}
})();
(async() => {
for await(const chunk of p.stderr.readable) {
console.log(chunk, new TextDecoder().decode(chunk))
}
})();
await p.stdin.write(new TextEncoder().encode("Coming from stdin\n"));
await p.status();
现在您将看到该过程的输出。
关于shell - Deno:如何在子进程完成之前运行 shell 命令并读取输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77028902/