【问题标题】:How to run a script located in a subdirectory? ImportError: No module named x如何运行位于子目录中的脚本? ImportError:没有名为 x 的模块
【发布时间】:2017-12-23 01:03:47
【问题描述】:

我的目录结构:

r/
 |___init__.py
 |
 |_d1/
 |   |___init__.py
 |   |_s1.py
 |
 |_d2/
     |___init__.py
     |_s2.py

s1.py 的内容:

a = 1

print(a)

s2.py 的内容:

from d1.s1 import a

print(2 * a)

我导航到目录/r 并执行python3 d1/s1.py。终端打印1。当我执行python3 d2/s2.py 时,我收到错误ImportError: No module named 'd1'。如何执行脚本s2

【问题讨论】:

    标签: python scripting directory


    【解决方案1】:

    当你说,

    from d1.s1 import a
    

    Python 将首先查找名为 d1 的模块,然后在该模块中查找名为 s1 的模块,然后在该模块中查找名为 a 的对象(可能是常规 Python 对象或其他模块)。

    所以,

    from d1.s1 import a
    

    可以通过几种不同的方式发挥作用:

    -- d1/
        -- __init__.py
          -- s1.py          <-- contains a variable called "a"
    

    - d1/
        -- __init__.py
        -- s1/
            -- __init__.py
            -- a.py
    

    -- d1/
    |    -- __init__.py
        -- s1/
            -- __init__.py     <-- contains a variable called "a"
    

    在您的情况下 init.py 仅在 d1 和 s1 和 s2 位于同一目录中时才有效。

    如果要从另一个子目录 d1 导入模块 s1,请确保 sys 路径中的目录 d1。

    将d1添加到系统路径

    sys.path.append('path_to_directory/d1') 
    

    【讨论】:

    • 我不太明白。我如何使它按原样工作? IE。在 /r 我执行一些命令并且脚本 s2.py 有效吗?通常我有类似的文件夹结构, d2 是测试。当我执行python3 -m unittest discover 时,它不知何故知道如何进行导入。
    • @wtaga 那么目录 r/d1 不在 sys.path 中
    猜你喜欢
    • 2015-02-06
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 2012-02-25
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多