简体   繁体   English

如何测试是否导入了一个python模块?

[英]how to test if one python module has been imported?

How to test if a module has been imported in python? 如何测试模块是否已在python中导入?

for example I need the basics: 例如,我需要基础知识:

if not has_imported("sys"):
   import sys

also

if not has_imported("sys.path"): 
   from sys import path

Thanks! 谢谢!

Rgs. RGS。

Thanks for all of your comments: the code been pasted here. 感谢您的所有评论:代码已粘贴在此处。 auto import all sub modules in a folder then invoke same name functions - python runtime inspect related 自动导入文件夹中的所有子模块然后调用相同的名称函数 - python runtime inspect相关

If you want to optimize by not importing things twice, save yourself the hassle because Python already takes care of this. 如果你想通过不导入两次来优化,那就省去麻烦了,因为Python已经解决了这个问题。

If you need this to avoid NameErrors or something: Fix your sloppy coding - make sure you don't need this, ie define (import) everything before you ever use it (in the case if imports: once, at startup, at module level). 如果您需要这样来避免NameErrors或其他:修复您的草率编码 - 确保您不需要它,即在您使用之前定义(导入)所有内容(如果是导入:一次,在启动时,在模块级别)。

In case you do have a good reason: sys.modules is a dictionary containing all modules already imported somewhere. 如果你有充分的理由: sys.modules是一个包含已在某处导入的所有模块的字典。 But it only contains modules, and because of the way from <module> import <variable> works (import the whole module as usual, extract the things you import from it), from sys import path would only add sys to sys.modules (if it wasn't already imported on startup). 但是它只包含模块,并且由于from <module> import <variable>工作方式(像往常一样导入整个模块,从中导出从中导入的东西), from sys import path只会将sys添加到sys.modules (如果它尚未在启动时导入)。 from pkg import module adds pkg.module as you probably expect. from pkg import module添加pkg.module如您所料。

I feel the answer that has been accepted is not fully correct. 我觉得已经接受的答案并不完全正确。

Python still has overhead when importing the same module multiple times. 多次导入同一模块时,Python 仍然有开销 Python handles it without giving you an error , sure, but that doesn't mean it won't slow down your script. Python肯定会处理它而不会给你一个错误 ,但这并不意味着它不会减慢你的脚本速度。 As you will see from the URL below, there is significant overhead when importing a module multiple times. 正如您将从下面的URL中看到的那样,多次导入模块时会产生很大的开销。

For example, in a situation where you may not need a certain module except under a particular condition, if that module is large or has a high overhead then there is reason to import only on condition. 例如,在某种情况下,除非在特定条件下,您可能不需要某个模块,如果该模块很大或开销很大,则有理由仅在条件下导入。 That does not explicitly mean you are a sloppy coder either. 这并没有明确表示你是一个草率的编码器。

https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Import_Statement_Overhead https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Import_Statement_Overhead

from sys import modules
try:
    module = modules[module_name]
except KeyError:
    __import__('m')   

this is my solution of changing code at runtime! 这是我在运行时更改代码的解决方案!

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

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