python - 导入脚本时是否会继续导入
问题描述
据我了解,当您从另一个脚本导入要运行的脚本时,导入将延续到新脚本。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 等)
解决方案
您仍然需要import pandas as pd
等,slow_exchange_bound
以便该名称pd
在 的全局命名空间中可用slow_exchange_bound
。“结转”来自模块仅评估一次的事实;随后的导入sys.modules
已经找到了模块,只需将模块的引用添加到相关的命名空间。
推荐阅读
- javascript - FileReader - 如何将字符编码从 UTF-8 更改为 ANSI
- sql-server-2012 - 如何在T-Sql中以逗号分隔的另一列的值中查找一列的数值?
- php - 第二层exec不返回线程
- mysql - 在 MySQL 中给定两个或多个条件的列内求和
- java - UCDetector 未检测到 Eclipse Oxygen 中未使用的方法
- amazon-web-services - 将 IOT 主题集成到 AWS dynamoDB 根本不起作用
- jquery - 嵌套猫头鹰旋转木马 2 不工作
- dictionary - 在 PySpark 中使用 Map 解析和分配列名
- excel - 在记录集中添加新列
- java - 为什么 Hashtable 不允许空值?