Python 根据输入动态加载模块

发布于 2024-08-19 18:22:57 字数 498 浏览 5 评论 0原文

我编写了一个程序,它接收部分 rss 提要并输出完整的 rss 提要,但它是根据具体情况而定的。一个站点的配方与另一个站点的配方不同。所以我所做的就是查看域基本名称(例如 nyt 或 wsj)并根据该名称选择一个模块。尽管我需要事先加载每个模块,并为每个配方提供一个逻辑条件。

我需要的是一种将各个模块放在各自文件夹中的方法,当我解析出 url 基本名称时,我希望它查找该模块,加载它并采取一些操作。所以我希望主代码库独立于模块。我希望将来能够添加模块,并且永远不要触及与它们交互的代码部分。

这是一个代码示例

if "nyt" == feed:
        nyt.parser(posixpath.basename(url), urldir, rss_file_path, url, feed)

正如您所看到的,我调用了各个模块的解析器。我根据每个网站都有很多这样的内容。我想要reed feed,然后能够查找模块,加载它并调用它,然后如果它不存在,则报告它并尝试默认方法。

I wrote a program that takes in a partial rss feed and outputs a full one, but it is one a case by case basis. The recipe for one site is not the same as the recipe for the other. So what I do is look at the domain basename(for instance nyt or wsj) and choose a module based on that. Though I need to load each and every module before hand and have a logical condition for each recipe.

What I need is a way to just have the individual modules in their own respective folder and when I parse out the url basename I want it to look for the module, load it and take some action. So I want the main code base to be independent from the modules. I want to be able to add the modules in the future and never touch the portion of code which interact with them.

Here is a code example

if "nyt" == feed:
        nyt.parser(posixpath.basename(url), urldir, rss_file_path, url, feed)

As you can see I call the parser of the individual module. I have many of these based on each website. I want to reed feed and then be able to look for the module, load it and call it, and then if it doesn't exist report it and try the default method.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南巷近海 2024-08-26 18:22:57

听起来您正在寻找 __import__ 功能。此函数与 import 语句执行相同的操作,但允许您传递一个可能仅在运行时才知道的名称进行导入。

所以您可能会这样做:

parsemodule = __import__(feed)
parsemodule.parser(posixpath.basename(url), urldir, rss_file_path, url, feed)

您将希望捕获诸如 ImportError 之类的异常。

It sounds like you're looking for the __import__ function. This function does the same thing as the import statement, but allows you to pass a name to import that might only be known at runtime.

So you might do:

parsemodule = __import__(feed)
parsemodule.parser(posixpath.basename(url), urldir, rss_file_path, url, feed)

You will want to catch exceptions such as ImportError.

花开浅夏 2024-08-26 18:22:57

您可以使用 imp 模块

You can use the imp module.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文