使用node exec访问python文件中的函数
我不熟悉node的使用node exec访问python文件中的函数,python,node.js,child-process,Python,Node.js,Child Process,我不熟悉node的子进程,我正在尝试执行python并将其结果返回给node 我想使用exec,不是执行简单的命令,而是访问python文件并执行它 假设mypython.py是 try : import anotherPythonFile print('hello2') # anotherPythonFile.names().getNames() except Exception as e : print(e) 我尝试对此进行测试,并返回了hello2,但
子进程
,我正在尝试执行python并将其结果返回给node
我想使用exec,不是执行简单的命令,而是访问python文件并执行它
假设mypython.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);
})
如果这起作用,我将取消注释并执行另一个pythonfile.names().getNames()
这里的错误是什么
另外,我是否可以直接访问另一个pythonfile
,并以某种方式设置要执行的函数?我想做(举例)
这可能吗
谢谢下面是一个从Node.js运行Python脚本并读取其输出的示例: 你好,派伊
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}`)
});
运行node 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)
}
})
你好。是的,我也知道
spawn
,它非常灵活,但我正在试验exec
,我想知道我是否可以将exec
用于python文件。接下来将有一个大型python+节点项目,我想首先研究所有选项。所以exec
不是python文件的选择,只是spawn
?感谢you@codebot好的,我用execFile
和exec
又写了两个例子,给你一些spawn
的选项。你可能想把exec
变成一个承诺,这样你就可以等待了。你想举个例子吗?谢谢你的提示。最后一件事,可以在exec中定义输入参数和/或特定函数吗?类似于exec('python3/home/telmo/hello.py apythonfunctiontoexecuteargumentone-argumentTwo'
Thank)的东西我认为您必须使用execFile
或spawn
,至少在。
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)
}
})