代码之家  ›  专栏  ›  技术社区  ›  Suresh

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

  •  0
  • Suresh  · 技术社区  · 3 年前

    下面是我的maincall.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'
    
    2 回复  |  直到 3 年前
        1
  •  2
  •   Serge Ballesta    3 年前

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

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

    test_invoke 确实是一个包,在其模块的根目录下使用它没有什么不好的 假如 它可以从Python路径访问。

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

    • 重命名 main_call.py __main__.py
    • 将有问题的导入行替换为 from .invoke import end_invoke
    • 启动程序包为 python -m test_invoke 用于包含 测试_投票 或将该目录添加到 蟒蛇路径 环境变量

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

        2
  •  0
  •   Saurabh Verma    3 年前

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

    所以,请更换线路 from test_invoke.invoke import end_invoke 具有 from invoke import end_invoke