包含一个 .py 文件,仍然不会破坏 cronjob (Python,初学者)?
我正在构建一个服务,其中运行着一些用 Python 编写的 cronjobs。然而,这是我的第一个 Python 项目,所以我仍然是一个非常初学者。
我现在正在做的是,我在每个文件上处理数据库连接,所以基本上如果我想更改主机,我需要检查所有文件。我现在正在研究一种与 PHP-include()
类似的 Python 方法,这样我就可以包含一些常规内容而不是复制粘贴。
另外,Python 文件在 cronjob 中运行,因此该方法也应该适用于 cronjobs :)
I'm building a service, which has a few cronjobs running, written in Python. However, this is my first Python-project ever, so I'm still a very beginner.
What I'm doing now, is that I have my database-connection handled on every file, so basically if I wanted to change the host, I would need to go through all the files. I'm now looking into a PHP-include()
similar method for Python, so that I could include some general stuff instead of copy-pasting.
Also, the Python-files are ran in cronjob, so the method should work on cronjobs too :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果它实际上只是单个数据库连接的几个设置,只需将其放入 Python 模块中并将其导入到所有文件中即可。为什么要添加不需要的复杂性?
如果更复杂,请按照 @AdamMatan 的建议使用 ConfigParser 。
If it's really just a couple of settings for a single database connection, just put it in a Python module and import it in all of your files. Why add any complexity you don't need?
If it's more complicated, use
ConfigParser
as @AdamMatan suggested.使用外部配置文件,以及您的数据库连接(主机、名称、密码、数据库、 ...),并从 Python 脚本中读取配置文件。
这使得更改变得容易(即使对于非程序员),并且很好地遵守单一选择原则 。
示例:
db.cfg
db.py
执行结果:
Use an external configuration file, with your db connection (host, name, password, db, ...) in it, and read the configuration file from within the Python script.
This makes changes easy (even for non-programmers) and nicely complies with the Single Choice Principle.
Example:
db.cfg
db.py
Execution result:
如果需要调用
__import__()
,你做错了。您需要重构您的代码这样您就不再将数据库连接例程分散在整个代码库中。是的,将这些详细信息放在配置文件中会更好(+1 @Adam Matan),但首先您需要消除重复。从长远来看,这将为您省去很多痛苦。
If you need to call
__import__()
, you are doing it wrong.You need to refactor your code so that you no longer have the database connection routines scattered throughout your codebase. Yes, it would be even nicer to have these details in a configuration file (+1 @Adam Matan), but first you need to eliminate the duplication. This will save you a world of pain in the long run.