MacOS下Bash实现Chrome终端应用输入输出重定向问题
Chrome Headless REPL 输入输出重定向问题解决
原命令无效的原因
你用的原命令只重定向了标准输出(stdout),但Chrome Headless在--repl模式下,部分运行日志、错误信息会输出到标准错误(stderr),导致这部分内容没被捕获。另外--repl是交互式模式,没输入触发的话,可能不会产生预期的输出内容。
可行方案
1. 一次性输入输出方案
如果只需要单次输入并捕获所有输出(包括stdout和stderr),可以用这两种方式:
方式一:Here String 全输出重定向
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \ --headless --disable-gpu --repl https://www.google.com \ <<< $(echo 123) &> ./output.txt
&>会把stdout和stderr都重定向到文件,<<<用来传递一次性输入内容。
方式二:管道+tee 同时保留终端与文件输出
echo 123 \ | /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \ --headless --disable-gpu --repl https://www.google.com \ &> >(tee stdout.txt)
用&> >(tee ...)把所有输出(stdout+stderr)写入文件的同时,还能在终端看到输出。
2. 流式输入输出方案(修复版)
你之前的FIFO方案不能正常工作,是因为Chrome REPL会等待输入流的EOF才处理命令,或者FIFO的读写需要异步处理。可以用后台进程拆分输入输出操作:
# 创建命名管道 mkfifo chrome_in chrome_out # 后台启动Chrome,绑定管道(同时捕获stdout和stderr) /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \ --headless --disable-gpu --repl https://www.google.com \ < chrome_in &> chrome_out & # 实时查看输出(后台运行) tail -f chrome_out & # 发送命令到Chrome REPL echo "123" > chrome_in echo "document.title" > chrome_in # 结束时清理资源 # kill %1 %2 # 终止Chrome和tail进程 # rm chrome_in chrome_out # 删除管道文件
这样就能实现实时交互:Chrome后台运行后,tail -f可以实时看输出,通过echo ... > chrome_in随时发送命令,不用关闭流就能处理输入。
Node.js集成提示
如果要在Node.js里做后续开发,直接用child_process模块创建子进程就行,不用依赖文件或FIFO:
const { spawn } = require('child_process'); // 启动Chrome Headless REPL const chrome = spawn( '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', ['--headless', '--disable-gpu', '--repl', 'https://www.google.com'] ); // 监听输出 chrome.stdout.on('data', (data) => { console.log('Chrome输出:', data.toString()); }); chrome.stderr.on('data', (data) => { console.log('Chrome错误/日志:', data.toString()); }); // 发送命令 chrome.stdin.write('123\n'); chrome.stdin.write('document.title\n');
内容的提问来源于stack exchange,提问作者Obscurus Grassator
相关产品推荐
相关产品推荐

