无法要求(' child_process')。spawn,控制台说spawn不是函数,Python-Shell节点包

时间:2016-06-23 20:57:11

标签: node.js child-process spawn

我正在尝试使用外部包:

npm install [python-shell][1]

现在,我只有基本的js文件以及包附带的示例:

console.log('hey in main.js')
var PythonShell = require('python-shell');

PythonShell.run('./my_script.py', function (err) {
  if (err) throw err;
  console.log('finished running python script');
});

my_script.py等一起

当我启动服务器时,console.log说:

Uncaught TypeError: spawn is not a function

在python-shell包的index.js中,正确需要spawn(similar case):

var spawn = require('child_process').spawn;

后来,它在包中使用如下:

this.childProcess = spawn(pythonPath, this.command, options);

但是,spawn似乎确实是一个功能:

master$>node
> require('child_process')
{ ChildProcess: 
   { [Function: ChildProcess]
     super_: 
      { [Function: EventEmitter]
        EventEmitter: [Circular],
        usingDomains: true,
        defaultMaxListeners: 10,
        init: [Function],
        listenerCount: [Function] } },
  fork: [Function],
  _forkChild: [Function],
  exec: [Function],
  execFile: [Function],
  spawn: [Function],
  spawnSync: [Function: spawnSync],
  execFileSync: [Function: execFileSync],
  execSync: [Function: execSync] }

所以我不确定为什么控制台说这不是一个功能。

2 个答案:

答案 0 :(得分:3)

我遇到了同样的问题,尝试运行这样的代码

var spawn = require('child_process')
var child = spawn('pwd')

会导致错误

 TypeError: spawn is not a function
at Object.<anonymous> (/home/sailor/advancedNode/child_cluster_exec/spawn.js:5:13)

然而,将spawn添加到require修复它

 var spawn = require('child_process').spawn
 var child = spawn('pwd')

OR

      var {spawn} = require('child_process')

这很好....

答案 1 :(得分:0)

在Windows下使用此功能:

const cp = require('child_process');
const cmd = cp.spwan('cmd');
cmd.on('exit',(data)=>{
  console.log(data);
});

spawn不是通常的“正常”功能,它没有其他默认名称字符串。