繁体   English   中英

从文件导入模块时出现 python 问题

[英]python issue while importing a module from a file

下面是我的 main_call.py 文件

from flask import Flask, jsonify, request

from test_invoke.invoke import end_invoke

from config import config

app = Flask(__name__)


@app.route("/get/posts", methods=["GET"])
def load_data():
    
        res = "True"
        
        # setting a Host url
        host_url = config()["url"]

        # getting request parameter and validating it 
        generate_schedule= end_invoke(host_url)

        if generate_schedule == 200:
            return jsonify({"status_code": 200, "message": "success"})
        elif generate_schedule == 400:
            return jsonify(
                {"error": "Invalid ", "status_code": 400}
            )

    

if __name__ == "__main__":
    app.run(debug=True)

调用.py

import requests
import json
import urllib
from urllib import request, parse
from config import config
from flask import request




def end_invoke(schedule_url):

    

    

    headers = {
        "Content-Type":"application/json",
    }
    schedule_data = requests.get(schedule_url, headers=headers)

    if not schedule_data.status_code // 100 == 2:
        error = schedule_data.json()["error"]
        print(error)
        
        return 400
    
    else:
        success = schedule_data.json()
        
        return 200

树结构

test_invoke
├── __init__.py
├── __pycache__
│   ├── config.cpython-38.pyc
│   └── invoke.cpython-38.pyc
├── config.py
├── env.yaml
├── invoke.py
└── main_call.py

但是当我运行时,我得到了没有找到模块的错误

 python3 main_call.py 
Traceback (most recent call last):
  File "main_call.py", line 3, in <module>
    from test_invoke.invoke import end_invoke
ModuleNotFoundError: No module named 'test_invoke'

Python 在其 Python 路径中查找包和模块。 它搜索(按顺序):

  • 当前目录(可能不是当前 Python 模块的路径...)
  • PYTHONPATH环境变量的内容
  • 各种(实现和系统相关的)系统路径

由于test_invoke确实是一个 package,如果它可以从 Python 路径访问,那么在其模块的根目录下使用它没有什么先验的坏处。

但是恕我直言,直接启动驻留在 package 中的 python 模块总是一个坏主意。最好使 package 可访问,然后在 package 中使用相对导入:

  • main_call.py重命名为__main__.py
  • from.invoke import end_invoke替换有问题的导入行
  • 启动 package 作为python -m test_invoke为包含test_invoke的目录或将该目录添加到PYTHONPATH环境变量之后

这样,即使您从不同的当前目录启动程序,导入也会起作用。

您正在尝试导入当前目录中可用的文件。

因此,请将from test_invoke.invoke import end_invoke行替换为from invoke import end_invoke

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM