简体   繁体   English

在 Python 中从另一个脚本导入

[英]Importing From Another Script in Python

My directory is as such:我的目录是这样的:

isds:
__init__.py
    jobs:
    __init__.py
        adhoc:
        __init__.py
        test.py
        test2.py

My two files look like this.我的两个文件看起来像这样。

test.py:测试.py:

import sys

x = 10

test2.py:测试2.py:

import sys
from isds.jobs.adhoc.test import *

print(x)

When I run "python3 test2.py" from the same directory as test2.py, I get this error: ModuleNotFoundError: No module named 'isds.jobs.adhoc.test'当我从与 test2.py 相同的目录中运行“python3 test2.py”时,出现此错误:ModuleNotFoundError: No module named 'isds.jobs.adhoc.test'

Why is this happening?为什么会这样? I have the init .py files and I think I have the absolute import statement correct... but maybe not?我有init .py 文件,我想我的绝对导入语句是正确的......但也许不是?

Thanks!谢谢!

由于您是从同一目录导入模块,因此您可以简单地导入使用。

from test import *

in order to import as a package then you need to run the file as a package, so you would navigate to the folder containing isds` and run:为了作为包导入,您需要将文件作为包运行,因此您将导航到包含 isds` 的文件夹并运行:

python -m isds.jobs.adhoc.test2

This runs the file as a module instead of a script, and since it gets indexed at the same level that it uses its own imports then the import mechanic you are using works as intended.这将文件作为模块而不是脚本运行,并且由于它在使用自己的导入的同一级别被索引,因此您正在使用的导入机制按预期工作。

If you want to support either running as a script or running as a module you would need something like this:如果你想支持作为脚本运行或作为模块运行,你需要这样的东西:

try:
    from isds.jobs.adhoc.test import *
except ModuleNotFoundError:
    from test import *

But this can lead to other issues like if a different module not found error occurs and then import test ends up importing something else entirely you can get confusing and misleading error messages, so I'd generally recommend just running all your stuff with the -m flag if you are writing packages.但这可能会导致其他问题,例如,如果发生未找到不同模块的错误,然后import test最终完全导入其他内容,您可能会得到令人困惑和误导性的错误消息,因此我通常建议只使用-m运行所有内容如果您正在编写包,请标记。

Also note this method works without any __init__.py files in python 3.7,4 .另请注意,此方法在 python 3.7,4无需任何__init__.py文件3.7,4 the requirement to add empty init files was removed a while ago I believe.我相信不久前删除了添加空 init 文件的要求。

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

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