在nodejs中从python激活虚拟环境

J. *_*Doe 7 python node.js raspberry-pi virtual-environment

我在树莓派 4 上有以下项目:我用 python 创建了一个人脸识别脚本,需要虚拟环境才能运行。该脚本打印出已检测到的人。

在 NodeJS 中,我想通过在节点(缩小版本)中运行脚本来接收答案:

const http = require("http");
const server = http.createServer((req, res) => {

var spawn = require('child_process').spawn,
py    = spawn('python', ['faceReg.py'],)
py.stdout.on('data', function(data){
  console.log('Data:' + data);

});
py.stdout.on('end', function(){
  console.log('Python ended');


 });

});
Run Code Online (Sandbox Code Playgroud)

当执行代码时,我立即得到一个“python结束”。

在我的 pi 上,当我在执行前运行以下命令时,我可以运行脚本:

source ~/.virtualenvs/cv2_env/bin/activate 
Run Code Online (Sandbox Code Playgroud)

python脚本基本上是:

stop = False
while(stop==False):
   print("Peter")
Run Code Online (Sandbox Code Playgroud)

更新

跑步时

py    = spawn('~/.virtualenvs/cv2_env/bin/python', ['faceReg.py'])
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

events.js:174
      throw er; // Unhandled 'error' event
      ^
Error: spawn ~/.virtualenvs/cv2_env/bin/python ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
    at onErrorNT (internal/child_process.js:415:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)
    at Function.Module.runMain (internal/modules/cjs/loader.js:757:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
Emitted 'error' event at:
    at Process.ChildProcess._handle.onexit (internal/child_process.js:246:12)
    at onErrorNT (internal/child_process.js:415:16)
    [... lines matching original stack trace ...]
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
Run Code Online (Sandbox Code Playgroud)

这是我的文件系统: 在此输入图像描述

我究竟做错了什么?

Bra*_*ing 7

激活虚拟环境必须在脚本本身中完成。超出此范围将不会生效。

与此处的答案类似,您只想执行虚拟环境中列出的 Python 运行时。该问题引用了pip,但您基本上可以将其替换为您想要的 Python 版本(存在于您的虚拟环境中)。换句话说,您将替换这一行:

py    = spawn('python', ['faceReg.py'],)
Run Code Online (Sandbox Code Playgroud)

有了这一行:

py    = spawn('/home/youruser/.virtualenvs/cv2_env/bin/python', ['faceReg.py'],)
Run Code Online (Sandbox Code Playgroud)

注意:如果失败,您可能需要更改/home/youruser/.virtualenvs/cv2_env/bin/python为您正在寻找的任何版本的 Python,例如/home/youruser/.virtualenvs/cv2_env/bin/python3/home/youruser/.virtualenvs/cv2_env/bin/python3.7.