问题描述
我想导出名为 completed 的变量,以便我可以在 PythonShell.run 函数之外使用它。有什么建议吗?这是我的代码。
python 代码
#test.py
import sys
def hello(a,b):
print("hello and that's your sum:",a + b)
if __name__ == "__main__":
a = int(sys.argv[1])
b = int(sys.argv[2])
hello(a,b)
javascript 代码
let {PythonShell} = require('python-shell')
let options = {
mode: 'text',pythonoptions: ['-u'],// get print results in real-time
args: [1414,2323]
};
PythonShell.run('./photos/filterPhoto/test.py',options,function (err,results) {
if (err) throw err;
const completed = results;
///results: ["hello and that's your sum: 3737"]
});
console.log(completed)
Error : ReferenceError: completed is not defined
解决方法
尝试使用 JSPyBridge/pythonia 调用 Python 脚本:
通过 ES6 导入:
import { python } from 'pythonia'
const test = await python("./test.py")
await test.hello(2,3)
python.exit()
或者通过 CommonJS 导入:
const { python } = require('pythonia')
async function main() {
const test = await python("./test.py")
await test.hello(2,3)
}
main().then(() => python.exit())