我是node的child_process
的新手,我正在尝试执行python并将其结果返回给node
我想使用exec,不是为了执行一个简单的命令,而是为了访问一个python文件并执行它
说我的python.py
是
try :
import anotherPythonFile
print('hello2')
# anotherPythonFile.names().getNames()
except Exception as e :
print(e)
我尝试对此进行测试并返回hello2
,但一无所获
exec('D:\prjt\test\python.py', (er, stdout, stderr)=>{
console.log('exec test', stdout);
})
如果这可以,我将取消注释并执行anotherPythonFile.names().getNames()
这里的错误是什么?
另外,我是否可以直接访问anotherPythonFile
并以某种方式设置我想要执行的函数? 我想做的(例子)
exec('D:\prjt\test\anotherPythonFile.py.names().getNames()', (er, stdout, stderr)=>{
console.log('exec test', stdout);
})
这可能吗?
谢谢
下面是一个从node.js运行Python脚本并读取其输出的示例:
你好。py
print("Hello from Python!")
main.js
const { spawn } = require('child_process');
const py = spawn('python3', ['/home/telmo/hello.py'])
py.stdout.on('data', (data) => {
console.log(`${data}`)
});
运行节点main.js
返回:
Hello from Python!
也可以使用execfile
代替spawn
:
const { execFile } = require('child_process');
const py = execFile('python3', ['/home/telmo/hello.py'], (error, stdout, stderr) => {
if (error || stderr) {
// Handle error.
} else {
console.log(stdout)
}
})
或exec
:
const { exec } = require('child_process');
const py = exec('python3 /home/telmo/hello.py', (error, stdout, stderr) => {
if (error || stderr) {
// Handle error.
} else {
console.log(stdout)
}
})