node.jsの「python-shell」モジュールを利用して、pythonファイルを実行するプログラムを作成しています。
その際、pythonファイルが、今後いくつも増えても対応できるように、python-shellを簡易的に使用できるような関数を作成しようとした段階で、pythonから返却されたデータを呼び出し元へどうやって返せばよいのかがわからず、質問させていただきました。
python-shellがどうこうというよりも、コールバック関数の値の返却の仕方の問題なのかもしれませんが、ご教授いただけましたら幸いです。
前提・実現したいこと
pythonから返ってきた値を呼び出し元へ返却するプログラムの作成。
該当のソースコード
python
1# hello.py 2# セットされた名前にHello!を付与して返却するプログラム 3import sys 4 5name = sys.stdin.readline().split('\n') 6 7def craeteMessage(name): 8 return f'Hello! {name}' 9 10print(craeteMessage(name[0])) 11
Node.js
1// python_shell.js 2const {PythonShell} = require('python-shell'); 3 4function hello_message(name) { 5 const pyshell = new PythonShell('./python/hello.py'); 6 pyshell.send(name); 7 let result; 8 pyshell.on('message', function (res) { 9 //console.log(res) // Hello! testは表示されるが、undefinedの後に表示される 10 result = res; 11 }); 12 return result; 13} 14console.log(hello_message('test'));
bash
1> node .\python_shell.js 2undefined # Hello! test が表示されることを期待しています。
なお、ディレクトリ構成は、以下の通りです。
app / python / hello.py / python_shell.js
あなたの回答
tips
プレビュー