简体   繁体   English

在 VS Code 和 virtualenv 中使用 Azure 函数时找不到 Numpy 模块

[英]Numpy module not found when working with Azure Functions in VS Code and virtualenv

I'm new to working with azure functions and tried to work out a small example locally, using VS Code with the Azure Functions extension.我刚开始使用 azure 函数,并尝试在本地创建一个小示例,使用 VS Code 和 Azure 函数扩展。

Example:例子:

# First party libraries
import logging

# Third party libraries
import numpy as np
from azure.functions import HttpResponse, HttpRequest


def main(req: HttpRequest) -> HttpResponse:
    seed = req.params.get('seed')

    if not seed:
        try:
            body = req.get_json()
        except ValueError:
            pass
        else:
            seed = body.get('seed')

    if seed:
        np.random.seed(seed=int(seed))
        r_int = np.random.randint(0, 100)
        logging.info(r_int)
        return HttpResponse(
            "Random Number: " f"{str(r_int)}", status_code=200
            )
    else:
        return HttpResponse(
            "Insert seed to generate a number",
            status_code=200
            )

When numpy is installed globally this code works fine.当全局安装 numpy 时,此代码工作正常。 If I install it only in the virtual environment, however, I get the following error:但是,如果我仅在虚拟环境中安装它,则会出现以下错误:

*Worker failed to function id 1739ddcd-d6ad-421d-9470-327681ca1e69.
[15-Jul-20 1:31:39 PM] Result: Failure
Exception: ModuleNotFoundError: No module named 'numpy'. Troubleshooting Guide: https://aka.ms/functions-modulenotfound*

I checked multiple times that numpy is installed in the virtual environment, and the environment is also specified in the.vscode/settings.json file.多次查看,虚拟环境中安装了numpy,在.vscode/settings.json文件中也指定了环境。

pip freeze of the virtualenv "worker_venv": pip 冻结虚拟环境“worker_venv”:

$ pip freeze
azure-functions==1.3.0
flake8==3.8.3
importlib-metadata==1.7.0
mccabe==0.6.1
numpy==1.19.0
pycodestyle==2.6.0
pyflakes==2.2.0
zipp==3.1.0

.vscode/settings.json file: .vscode/settings.json 文件:

{
  "azureFunctions.deploySubpath": ".",
  "azureFunctions.scmDoBuildDuringDeployment": true,
  "azureFunctions.pythonVenv": "worker_venv",
  "azureFunctions.projectLanguage": "Python",
  "azureFunctions.projectRuntime": "~2",
  "debug.internalConsoleOptions": "neverOpen"
}

I tried to find something in the documentation, but found nothing specific regarding the virtual environment.我试图在文档中找到一些东西,但没有发现任何关于虚拟环境的具体信息。 I don't know if I'm missing something?我不知道我是否遗漏了什么?

EDIT: I'm on a Windows 10 machine btw编辑:顺便说一句,我在 Windows 10 机器上

EDIT: I included the folder structure of my project in the image below编辑:我在下图中包含了我的项目的文件夹结构

在此处输入图像描述

EDIT: Added the content of the virtual environment Lib folder in the image below编辑:在下图中添加了虚拟环境 Lib 文件夹的内容

在此处输入图像描述

EDIT: Added a screenshot of the terminal using the pip install numpy command below编辑:使用下面的pip install numpy命令添加了终端的屏幕截图

在此处输入图像描述

EDIT: Created a new project with a new virtual env and reinstalled numpy, screenshot below, problem still persists.编辑:使用新的虚拟环境创建了一个新项目并重新安装了 numpy,如下截图,问题仍然存在。

在此处输入图像描述

EDIT: Added the launch.json code below编辑:在下面添加了 launch.json 代码

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Attach to Python Functions",
      "type": "python",
      "request": "attach",
      "port": 9091,
      "preLaunchTask": "func: host start"
    }
  ]
}

SOLVED解决了

So the problem was neither with python, nor with VS Code.所以问题既不在于 python,也不在于 VS Code。 The problem was that the execution policy on my machine (new laptop) was set to restricted and therefore the .venv\Scripts\Activate.ps1 script could not be run.问题是我的机器(新笔记本电脑)上的执行策略设置为受限,因此无法运行.venv\Scripts\Activate.ps1脚本。

To resolve this problem, just open powershell with admin rights and and run set-executionpolicy remotesigned .要解决此问题,只需使用管理员权限打开 powershell 并运行set-executionpolicy remotesigned Restart VS Code and all should work fine重启 VS Code,一切正常

I didn't saw the error, due to the many logging in the terminal that happens when you start azure. I'll mark the answer of @HuryShen as correct, because the comments got me to the solution.我没有看到错误,因为当您启动 azure 时在终端中发生了多次登录。我将@HuryShen 的答案标记为正确,因为评论让我找到了解决方案。 Thank all of you guys谢谢你们所有人

For this problem, I'm not clear if you met the error when run it locally or on azure cloud.对于这个问题,我不清楚您是在本地运行还是在 azure 云上运行时遇到错误。 So provide both suggestions for these two situation.因此,针对这两种情况提供两种建议。

1. If the error shows when you run the function on azure, you may not have installed the modules success. 1 、如果在azure上运行function时出现错误,可能是模块没有安装成功。 When deploy the function from local to azure, you need to add the module to requirements.txt (as Anatoli mentioned in comment).将 function 从本地部署到 azure 时,您需要将模块添加到requirements.txt (正如 Anatoli 在评论中提到的那样)。 You can generate the requirements.txt automatically by the command below:您可以通过以下命令自动生成requirements.txt

pip freeze > requirements.txt

After that, we can find the numpy==1.19.0 exist in requirements.txt .之后,我们可以在requirements.txt中找到numpy==1.19.0 在此处输入图像描述

Now, deploy the function from local to azure by the command below, it will install the modules success on azure and work fine on azure. Now, deploy the function from local to azure by the command below, it will install the modules success on azure and work fine on azure.

func azure functionapp publish <your function app name> --build remote

2. If the error shows when you run the function locally. 2.如果在本地运行function时出现错误。 Since you provided the modules installed in worker_venv , it seems you have installed numpy module success.由于您提供了安装在worker_venv中的模块,看来您已成功安装numpy模块。 I also test it in my side locally, install numpy and it works fine.我也在本地测试它,安装numpy并且它工作正常。 So I think you can check if your virtual environment( worker_venv ) exist in the correct location.所以我认为你可以检查你的虚拟环境( worker_venv )是否存在于正确的位置。 Below is my function structure in local VS code, please check if your virtual environment locates in the same location with mine.下面是我在本地VS代码中的function结构,请检查您的虚拟环境是否与我的位于同一位置。

在此处输入图像描述

----- Update ------ -----更新------

Run the command to to set execution policy and then activate the virtual environment:运行命令来设置执行策略,然后激活虚拟环境:

set-executionpolicy remotesigned
.venv\Scripts\Activate.ps1

I could solve my issue uninstalling python3 (see here for a guide https://stackoverflow.com/a/60318668/11986067 ).我可以解决卸载 python3 的问题(参见此处的指南https://stackoverflow.com/a/60318668/11986067 )。

After starting the app functions via F5 or func start , the following output was shown:通过 F5 或func start应用程序功能后,显示以下 output:

在此处输入图像描述

This version was incorrect.这个版本不正确。 I have chosen python 3.7.0 when creating the project in the Azure extension.我在Azure扩展中创建项目时选择了python 3.7.0。 After deleting this python3 version, the correct version was shown and the Import issue was solved:删除此 python3 版本后,显示正确的版本并解决导入问题:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Microsoft Azure 函数:值“提供者”不能是 null,VS 代码生成 Python 函数应用程序 - Microsoft Azure Functions: value 'provider' cannot be null with VS Code generated Python Functions App VS Code Azure 部署 Python Http 触发器 function 失败 - 未找到 GLIB_2.27 - VS Code Azure deployment of Python Http Trigger function fails - GLIB_2.27 not found Azure 中的 Nlog 函数在通过 DI 注入时不起作用 - Nlog in Azure functions not working when injected via DI 通过 VS 代码部署 Azure Function 时无法同步触发器 - Cant sync triggers when deploying Azure Function via VS code 找不到模块 python Azure function - module not found python Azure function Azure 存储(经典)与 Azure 存储(V2)代码不适用于 V2 存储 - Azure Storage (classic) vs Azure Storage (V2) code not working for V2 storage “未找到存储连接字符串。” 当试图从 azure 功能核心工具中列出持久的 function 实例时 - 'No storage connection string found.' when trying to list durable function instances from azure functions core tools 通过 Function Azure VS Code 发送 RestClient - Send RestClient through Function Azure VS Code 无法使用 Azure ML 工作区 + VS 代码调试代码 - Cannot debug code with Azure ML workspace + VS Code 未找到 SonarQube 的 Azure 管道中的报告代码覆盖率 - Report Code Coverage in Azure Pipeline for SonarQube not found
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM