![](/img/trans.png)
[英]Is there a way to automatically verify all imports in a Python script without running it?
[英]Check if all imports are possible without running a script
我有一个巨大的项目,其中有很多 python 文件。 不幸的是,这个项目没有被测试正确覆盖,我们正面临着...进口的问题:)
我的目标是执行所有 python 脚本的“试运行”(不执行它们) ,以确保正确导入所有模块(尤其是这些本地模块)并列出所有无法导入的所有无效脚本。
让我给你第一个例子(script1.py):
from NON_EXISTING_local_module import non_existing_class
import time
def test_something():
time.sleep(10)
test_something()
NON_EXISTING_local_module 的导入是不可能的,就像它在 Python 中通过 ImportError 异常正常完成一样(script1.py 标记为无效)
第二个例子(script2.py):
from EXSISTING_local_module import existing_class
import time
def test_something():
time.sleep(10)
test_something()
在这里我想看到一切都很好(导入没有问题)并且方法 test_something() 根本没有执行(不需要等待 10 秒) (script2.py 标记为有效)
我知道有一个选项可以执行并获得它的结果:
python -c 'import module'
但它不适用于本地模块
更重要的是,RobotFramework 具有 --dryrun 之类的选项,如此处所述: http ://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#dry-run 我正在寻找完全相同的解决方案,但用于纯 python 脚本。
非常感谢您提供任何提示!
您可以使用 try-except ,例如:
import time
try:
import NON_EXISTING_local_module
except ImportError:
time.sleep(10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.