简体   繁体   English

Python:导入库/模块后打印自定义消息

[英]Python: Printing custom message after importing library / module

I have a web-app on which user will be writing a Python snippet. 我有一个Web应用程序,用户将在其上编写Python代码段。

I want to add a custom message whenever user imports a library. 我想在用户导入库时添加自定义消息。 For example, if user's code is something as below 例如,如果用户代码如下

import pandas
import os
from subprocess import Popen, PIPE

Then the output should have: 然后输出应具有:

You have imported pandas
You have imported os
You have imported Popen
You have imported PIPE

The user's code can be dynamic, and can actually import any library. 用户的代码可以是动态的,并且实际上可以导入任何库。

The only way I can think of right now is to use try except. 我现在唯一想到的方法是使用tryexcept。 You can take user input (the library name) as string and then: 您可以将用户输入(库名称)作为字符串,然后:

import importlib

lib_to_import = 'math'


try:
    importlib.import_module(lib_to_import)
    print("You have imported {}.".format(lib_to_import))
except:
    print("Something went wrong when importing {}.".format(lib_to_import))

You can wrap the above into a function and call it every time when the user imports a library. 您可以将以上内容包装到一个函数中,并在每次用户导入库时调用它。

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

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