如何导入已从父脚本导入的库?

How can I import a library that was already imported from a parent script?

这个问题不知道怎么解释清楚准确...

但是我正在尝试 运行 一个主脚本 (main.py),它导入了几个库(比如 'os' 模块)并且这个脚本应该导入另一个子脚本( child.py)。

问题是 'child.py' 必须使用此 'os' 模块,但无法从 'main.py'.

获取

我尝试 运行 'main.py' 并得到: NameError: name 'os' is not definied.

我的目录结构:

main/
|__ main.py
|__ sub/
    |__ child.py
    |__ __init__.py

[main.py]内容:

import os
from sub.child import function

function()

[child.py]内容:

def function:
    os.system('clear')
    <more code that require 'os' module>

我在这里错过了什么? 我正在尝试从 'main.py' 导入所有库以避免在 运行 另一个脚本时等待太久(不希望他们之后导入很多库,我想从主导入所有内容文件)。

I'm trying to import all libraries from the 'main.py' to avoid waiting to much when running another scripts (don't want them importing a lot of libraries after, I want to import everything from the main file).

这不是它的工作原理。您应该在实际使用它的模块中导入一个模块,并且只在那里使用。

所以需要在子模块中导入os模块才能使用:

# child.py
import os

def function():
    os.system('clear')
    # more code that uses `os`

如果在 main.py 中实际上没有使用 os,则不应将其导入那里:

# main.py
from sub.child import function

function()

也正如@user10987432指出的那样;如果您担心 import 语句会减慢您的代码速度,那么您就搞错了优先级。它不仅是一种过早优化的形式,而且最重要的是,甚至很难想到 import 语句是瓶颈的时间 - 也就是说 - 这可能是不可能的,而且它是非 -问题。

我认为您的代码最初没有 import os 行,但您在源代码中更正了这一点并重新导入了文件。

问题是 Python 缓存了模块。如果您多次导入,则每次返回同一个模块时都不会重新读取它。您在第一次导入时所犯的错误将继续存在。

要在编辑后重新导入 imtools.py 文件,必须使用 reload(imtools)。