python - 从另一个非子文件夹导入 python 文件

标签 python python-3.x python-import

我想要什么

我正在使用 Visual Studio Code 和 Python 3.7.0,我只是想将另一个 Python 文件从另一个文件夹导入到我的 python 文件中


详情

这是我的文件夹结构

root/
    dir1/
        data.txt
        task11.py
        task12.py
    dir2/
        data.txt
        task21.py
        task22.py
    Helpers/
        FileHelper/
            ReadHelper.py

那么一个简短的解释:

  • 我在每个“任务”文件中使用相同的函数
  • 我没有将函数放在每个“任务”文件中,而是在函数存在的地方创建了一个帮助文件
  • 我想将帮助程序文件“ReadHelper.py”导入到我的任务文件中

我尝试过的

例如在文件 task11.py 中:

  • 从 Helpers.FileHelper.ReadHelper 导入 *

  • >
    import os, sys
    parentPath = os.path.abspath("../../")
    if parentPath not in sys.path:
        sys.path.insert(0, parentPath)
    from Helpers.FileHelper.ReadHelper import *
    
  • >
    import os, sys
    sys.path.append('../../')
    from Helpers.FileHelper.ReadHelper import *
    

以上解决方案均无效,因为我总是以错误告终: ModuleNotFoundError: 没有名为“Helpers”的模块

我也试过:

  • 从 ..Helpers.FileHelper.ReadHelper 导入 *

但它以错误结束:ValueError: attempted relative import beyond top-level package

那么如何将文件 ReadHelper.py 导入到我的任务文件中呢?


附言

有一些类似的问题,但它们真的很老,答案对我没有帮助。


更新1

Visual Studio 代码中有一个选项,vscode python command如果我使用此导入 from Helpers.FileHelper import ReadHelper 运行此命令,则不会生成任何错误并且代码会完美执行。

一个缺点是这个交互式窗口启动速度很慢,并且无法处理输入。

我也尝试了@Omni 的回答:

$> python -m root.dir1.task11

成功了!但正如他所说,有一个缺点:在终端中输入速度很慢。

所以我尝试在 Visual Studio Code 中创建一个任务,该任务可以对我当前所在的文件执行上述 shell 命令,但没有成功。

你知道如何在 vscode 中创建一个任务来运行上面的命令吗?


我还尝试在每个目录下添加 __init__.py 文件,这样它们就会被视为包 Python3 tutorial - 6.4 Module Packages .但这没有帮助,并且发生了同样的错误。


更新2

我想出了一种方法,使拥有这样的文件夹结构变得非常容易,并使导入在终端中正常工作。

基本上我所做的是:

  • 创建了一个 Python 脚本
  • 在 visual studio 代码中创建了一个任务

有了这个,我现在可以运行我的 python 文件,只需按 cmd + shift + B 即可导入。


解释

Visual Studio 任务:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Run python file",
            "type": "shell",
            "command": "python3 /PATH_TO_ROOT_FOLDER/run_python_file.py ${file}",
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                "reveal": "always",
                "panel": "new",
                "focus": true
            }
        }
    ]
}

我们要重点关注的部分是:

"command": "python3/PATH_TO_ROOT_FOLDER/run_python_file.py ${file}",

  • 这部分运行我在根文件夹中创建的新 python 文件,并将事件文件的路径作为参数传递

python 脚本:

import os, sys

# This is a argument given trough a shell command
PATH_TO_MODULE_TO_RUN = sys.argv[1]

ROOT_FOLDER = "root/"

def run_module_gotten_from_shell():
    # Here I take only the part of the path that is needed
    relative_path_to_file = PATH_TO_MODULE_TO_RUN.split(ROOT_FOLDER)[1]
    
    # Creating the shell command I want to run
    shell_command = createShellCommand(relative_path_to_file)

    os.system(shell_command)


# Returning "python3 -m PATH.TO.MODULE"
def createShellCommand(relative_path_to_file):
    part1 = "python3"
    part2 = "-m"

    # Here I change the string "dir1/task11.py" => "dir1.task11"
    part3 = relative_path_to_file.replace("/", ".")[:-3]

    shell_command = "{:s} {:s} {:s}".format(part1, part2, part3)
    return shell_command

run_module_gotten_from_shell()
  • 此 python 脚本获取事件文件的路径作为参数
  • 然后它创建路径的 shell 命令(shell 命令就像@kasper-keinänen 的回答)
  • 然后它运行该 shell 命令

通过这些修改,我可以运行根目录中的任何文件,并从根目录中的任何文件导入。

我只需按 cmd + shift + B 即可。

最佳答案

您可以尝试使用 -m 选项运行脚本,该选项允许使用 Python 模块命名空间 docs.python.org 定位模块。 .

如果您运行 task11.py 脚本,则:

$ python3 -m dir1.task11 

然后在 task11.py 中执行如下导入:

from Helpers.FileHelper.ReadHelper import *

关于python - 从另一个非子文件夹导入 python 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59147120/

相关文章:

python - 如何处理模块中的全局变量?

python-3.x - ImportError 与 from 。在简单的 python 文件上导入 x

python - 如何匹配原始字符串中的换行符?

python - 使用字符串和 python 列表参数从终端运行 shell 脚本

python-3.x - 如何从 python 中激活 pyvenv vitrualenv? (activate_this.py 被删除了?)

python - 检查是否有写过一次的不同字符

python - 不可哈希类型 : 'dict' in Flask app

python - python 中的 c++ map<int, int>

python - python 3.2.2中的碰撞检测和 mask

python - 无法使用顶级模块(源文件夹)启动我的导入语句