简体   繁体   English

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

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

the below is my main_call.py 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)

invoke.py调用.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

tree structure树结构

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

However when i run, i get the no module found error但是当我运行时,我得到了没有找到模块的错误

 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 looks for packages and modules in its Python path. Python 在其 Python 路径中查找包和模块。 It searches (in that order):它搜索(按顺序):

  • the current directory (which may not be the path of the current Python module...)当前目录(可能不是当前 Python 模块的路径...)
  • the content of the PYTHONPATH environment variable PYTHONPATH环境变量的内容
  • various (implementation and system dependant) system paths各种(实现和系统相关的)系统路径

As test_invoke is indeed a package, nothing is a priori bad in using it at the root for its modules provided it is accessible from the Python path.由于test_invoke确实是一个 package,如果它可以从 Python 路径访问,那么在其模块的根目录下使用它没有什么先验的坏处。

But IMHO, it is always a bad idea to directly start a python module that resides inside a package. Better to make the package accessible and then use relative imports inside the package:但是恕我直言,直接启动驻留在 package 中的 python 模块总是一个坏主意。最好使 package 可访问,然后在 package 中使用相对导入:

  • rename main_call.py to __main__.pymain_call.py重命名为__main__.py
  • replace the offending import line with from.invoke import end_invokefrom.invoke import end_invoke替换有问题的导入行
  • start the package as python -m test_invoke either for the directory containing test_invoke or after adding that directory to the PYTHONPATH environment variable启动 package 作为python -m test_invoke为包含test_invoke的目录或将该目录添加到PYTHONPATH环境变量之后

That way, the import will work even if you start your program from a different current directory.这样,即使您从不同的当前目录启动程序,导入也会起作用。

You are trying to import file available in the current directory.您正在尝试导入当前目录中可用的文件。

So, please replace line from test_invoke.invoke import end_invoke with from invoke import end_invoke因此,请将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