nodejs pythonshell,如何在run函数中导出变量

dauxcl2d  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(431)

我想导出名为completed的变量,以便使用pythonshell.run函数。有什么建议吗?这是我的密码。
python代码

  1. # test.py
  2. import sys
  3. def hello(a,b):
  4. print("hello and that's your sum:", a + b)
  5. if __name__ == "__main__":
  6. a = int(sys.argv[1])
  7. b = int(sys.argv[2])
  8. hello(a, b)

javascript代码

  1. let {PythonShell} = require('python-shell')
  2. let options = {
  3. mode: 'text',
  4. pythonOptions: ['-u'], // get print results in real-time
  5. args: [1414, 2323]
  6. };
  7. PythonShell.run('./photos/filterPhoto/test.py', options, function (err, results) {
  8. if (err) throw err;
  9. const completed = results;
  10. ///results: ["hello and that's your sum: 3737"]
  11. });
  12. console.log(completed)
  13. Error : ReferenceError: completed is not defined
0kjbasz6

0kjbasz61#

尝试使用jspybridge/pythonia调用python脚本:
通过es6导入:

  1. import { python } from 'pythonia'
  2. const test = await python("./test.py")
  3. await test.hello(2, 3)
  4. python.exit()

或通过commonjs导入:

  1. const { python } = require('pythonia')
  2. async function main() {
  3. const test = await python("./test.py")
  4. await test.hello(2, 3)
  5. }
  6. main().then(() => python.exit())

相关问题