首页 > 解决方案 > 导入脚本时是否会继续导入

问题描述

据我了解,当您从另一个脚本导入要运行的脚本时,导入将延续到新脚本。IE我在下面的脚本中导入pandas,现在pandas已经导入到新的脚本中了,所以我不再需要在新的脚本中写“import pandas as pd”了。

我知道有这个答案:Do a python module's imports need to be carry over when importing that module? 但这似乎是在讨论自定义导入(例如来自 app-helper)。我正在讨论更一般的导入,例如 os、pandas、numpy、time、sys 等。

import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import time
import sys

if input('Will you be using the free or bound state peaks? (Type in "Free" or "Bound")\n').lower() != 'free':
    import slow_exchange_bound
    sys.exit()

#rest of the script

但是,基于上面的脚本,如果我的 slow_exchange_bound 脚本中没有所有导入行,那么它就不能正常运行(即在 slow_exchange_bound 中,我必须重新输入 import os、import pandas 等)

标签: python

解决方案


您仍然需要import pandas as pd等,slow_exchange_bound以便该名称pd在 的全局命名空间中可用slow_exchange_bound。“结转”来自模块仅评估一次的事实;随后的导入sys.modules已经找到了模块,只需将模块的引用添加到相关的命名空间。


推荐阅读