gpt4 book ai didi

r - 从node.js调用shell脚本

转载 作者:太空宇宙 更新时间:2023-11-03 21:59:28 24 4
gpt4 key购买 nike

如何在 Node.js 中生成脚本并通过管道传输到 shell?

例如我可以创建这个文件,例如hello.R ,使其可执行 chmod +x hello.R并从命令行运行它,./hello.R :

#!/usr/bin/Rscript
hello <- function( name ) { return (sprintf( "Hello, %s", name ); })
cat(hello("World"));

我想做的是从 Node.js 做同样的事情。具体在内存中生成更复杂的 R 脚本(例如,使用模板等作为字符串),执行它(使用 execspawn ?),并读取 stdout

但是我不太清楚如何通过管道将脚本传输到 R。我尝试了这个(除其他外):

var rscript = [       
hello <- function( name ) { return (sprintf( "Hello, %s", name ); })
cat(hello("World"));
].join('\n');

var exec = require('child_process').exec;
exec(rscript, { shell: '/usr/bin/R'}, function(err, stdout, stderr) {
if (err) throw(err);
console.log(stdout);
});

但是,这失败了,因为看起来两者都不是 /usr/bin/R也不/usr/bin/Rscript了解-c开关:

最佳答案

查看child_process的nodejs文档。您应该能够像在终端上一样生成 RscriptR 命令,并通过 child 发送命令.stdin.

var c = require('child_process');
var r = c.spawn("R","");
r.stdin.write(rscript);
/* now you should be able to read the results from r.stdout a/o r.stderr */

关于r - 从node.js调用shell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30985794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com