【问题标题】:How to call python script from CasperJS如何从 CasperJS 调用 python 脚本
【发布时间】:2015-02-21 07:38:32
【问题描述】:

我正在尝试从 CasperJS 中调用 python 脚本并从 python 中获取输出。

casp = require('casper').create({
    verbose: true,
    logLevel: 'debug'
});

casp.start().then(function() {
  var cp = require('child_process');
    cp.execFile('/usr/bin/python','test.py', {},function(_,stdout,stderr){
        console.log(stdout);
        console.log(stderr);
    });
});

casp.run();

test.py 只是 print "hello world" atm 用于测试,但是当我运行这个脚本时它只是退出而不运行 python。

如果我用 --version 替换 test.py 参数,例如

cp.execFile('/usr/bin/python','--version', {},function(_,stdout,stderr){

然后我正确地获取了版本信息。我认为这一定是execFile中如何传递参数的问题,但不确定我应该做什么。

【问题讨论】:

  • 你是在 casperjs.cmd 还是其他地方更新了路径?
  • 不,没有对 casperjs 进行任何更改,全新下载

标签: javascript python phantomjs casperjs


【解决方案1】:

问题是您过早退出。一个空的casper.run() 意味着它会在所有casper 步骤执行完毕后立即退出。 child_process 模块不是 CasperJS 模块(它由 PhantomJS 提供),因此它无法知道它正在执行。

你可以简单地使用

casp.run(function(){});

防止退出。但是你可能需要终止 CasperJS 进程。

更好的方法是在执行完成时设置一个变量,然后才继续:

casp.start().then(function() {
  var finished = false;
  var cp = require('child_process');
  cp.execFile('/usr/bin/python','test.py', {},function(_,stdout,stderr){
    console.log(stdout);
    console.log(stderr);
    finished = true;
  });
  this.waitFor(function check(){
    return finished;
  }, function then(){
    // can stay empty
  });
}).run();

如果你想向外部程序传递多个参数,你应该使用一个数组作为execFile的第二个参数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 2014-03-18
    相关资源
    最近更新 更多