2

我想使用 node.js 来 spawn echo $(python --version),如果我把它放到我的终端它没有问题,我会得到类似的东西

Python 2.7.12

但是,如果我使用以下代码:

var spawn = require('child_process').spawn
var child = spawn('echo', ['$(python --version)'])
child.stdout.on('data', function(b){
    console.log(b.toString())
})

我只是将字符串文字回显给我:

$(python --version)

如何转义参数以正确生成,以便获得正确的输出。

编辑:我特别想使用 spawn 和 echo,我想知道是否有解决方案来正确逃避 spawn 参数......

4

2 回答 2

1

这应该可以帮助你。

var exec = require('child_process').exec;
exec('python --version', function(error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
  console.log('exec error: ' + error);
}
});

根据评论中的要求编辑:

var exec = require('child_process').exec;
exec('echo "Output goes here"', function(error, stdout) { //Replace echo with any other command.
    console.log(stdout);
});

输出:输出到这里。

可能想检查一下:How do I escape a string for a shell command in node?

于 2016-08-09T20:15:50.310 回答
1

我意识到我在这里参加聚会已经很晚了,但是当我自己寻找答案时:

我认为问题在于 spawn 命令默认不会在 shell 中运行(请参阅Node.js 文档)。我认为 Node.js 这样做是为了保护你,通过转义所有 shell 元字符,这就是你所经历的。如果将 shell 选项设置为 true,它将按需要工作,如下所示:

require('child_process').spawn('echo', ['$(python --version)'], {shell: true, stdio: 'inherit'});

注意:将 stdio 设置为从父进程继承意味着您不必自己记录 stdout :)

于 2017-12-21T07:05:03.430 回答