Node.jsからPythonを実行する

python-shellを使うとNode.jsからPythonのプログラムを実行できます。

本記事のサンプル実行の前提条件は次のとおりです。

  • Pythonインストール済み
  • 環境変数PATHにPython.exeへのパスを設定済み

インストール

npm install python-shell

サンプル構成

pyshell-test.js
/python
  |- sample.py

直接Pythonコードを実行する

PythonShell.runString()を利用します。

書式

PythonShell.runString(スクリプト, オプション, コールバック)

オプションにはPythonのパスやパラメータなどが設定できます。

実行例

const { PythonShell } = require('python-shell');

PythonShell.runString('x=1+1; print(x)', null, (err, result) => {
    if (err) throw err;

    console.log(result);
});
>node pyshell-test.js
[ '2' ]

Pythonファイルを実行する

PythonShell.run()を利用します。

書式

PythonShell.run(実行ファイル, オプション, コールバック)

実行例(引数なし)

const { PythonShell } = require('python-shell');

PythonShell.run('./python/sample.py', null, (err, result) => {
    if (err) throw err;

    console.log(result);
});
sample.py
x = 10
x += 10

print(x)
>node pyshell-test.js
[ '20' ]

実行例(引数あり)

引数を使用してPythonスクリプトを実行する場合は次のようにします。

const { PythonShell } = require('python-shell');

PythonShell.run('./python/sample.py', { args: [100] }, (err, result) => {
    if (err) throw err;

    console.log(result);
});
sample.py
import sys;
arg = int(sys.argv[1])

x = arg
x += 10

print(x)
>node pyshell-test.js
[ '110' ]

実行例(NodeとPythonとの間でデータを交換する)

const { PythonShell } = require('python-shell');

const pyshell = new PythonShell('./python/sample.py');

pyshell.on('message', (message) => {
    console.log(message);
});

pyshell.on('stderr', (stderr) => {
    console.log(stderr);
});

pyshell.on('error', (error) => {
    console.log(error);
});

pyshell.on('pythonError', (error) => {
    console.log(error);
});

pyshell.send(10);

pyshell.end((err, code, signal) => {
    if (err) throw err;

    console.log(`The exit code was: ${code}`);
    console.log(`The exit signal was: ${signal}`);
    console.log('finished');
});
sample.py
import sys;
arg_str = sys.stdin.readline()
arg = int(arg_str)

x = arg
x += 10

print(x)
>node pyshell-test.js
20
The exit code was: 0
The exit signal was: null
finished

Python側で出力(print())した内容がNodeにmessageイベントで通知されます。
次のように2回コールしても、最初の結果しか受信できません。(20のみ受信で、110は受信できない)

pyshell.send(10);
pyshell.send(100);
このエントリーをはてなブックマークに追加
にほんブログ村 IT技術ブログへ

スポンサードリンク

関連コンテンツ

コメント

メールアドレスが公開されることはありません。 が付いている欄は必須項目です