我想使用node.js来生成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参数的解决方案...
这应该可以帮到你。
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?
我意识到我在这里参加派对已经很晚了,但是我正在寻找自己的答案:
我相信问题是默认情况下spawn命令不会在shell中运行(请参阅Node.js Documentation)。我认为Node.js通过逃避所有shell metacharaters来保护你,这正是你所经历的。如果将shell选项设置为true,它将按预期工作,如下所示:
require('child_process').spawn('echo', ['$(python --version)'], {shell: true, stdio: 'inherit'});
注意:将stdio设置为从父进程继承意味着你不必自己登录stdout :)