- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在 github 上写一个软件。它基本上是一个带有一些额外功能的托盘图标。我想提供一段工作代码,而实际上不必让用户安装本质上是可选功能的依赖项,而且我实际上不想导入我不会使用的东西,所以我认为这样的代码将是“好的解决方案”:
---- IN LOADING FUNCTION ----
features = []
for path in sys.path:
if os.path.exists(os.path.join(path, 'pynotify')):
features.append('pynotify')
if os.path.exists(os.path.join(path, 'gnomekeyring.so')):
features.append('gnome-keyring')
#user dialog to ask for stuff
#notifications available, do you want them enabled?
dlg = ConfigDialog(features)
if not dlg.get_notifications():
features.remove('pynotify')
service_start(features ...)
---- SOMEWHERE ELSE ------
def service_start(features, other_config):
if 'pynotify' in features:
import pynotify
#use pynotify...
但是有一些问题。如果用户格式化他的机器并安装他的操作系统的最新版本并重新部署这个应用程序,功能会突然消失而没有警告。解决方案是在配置窗口中显示:
if 'pynotify' in features:
#gtk checkbox
else:
#gtk label reading "Get pynotify and enjoy notification pop ups!"
但如果这是一个 mac,我怎么知道我没有让用户去寻找他们永远无法填补的依赖项?
第二个问题是:
if os.path.exists(os.path.join(path, 'gnomekeyring.so')):
问题。我可以确定该文件在所有 Linux 发行版中始终称为 gnomekeyring.so 吗?
其他人如何测试这些功能?基本问题
try:
import pynotify
except:
pynotify = disabled
是代码是全局的,这些可能是乱七八糟的,即使用户不想要 pynotify....它还是被加载了。
那么人们认为解决这个问题的最佳方法是什么?
最佳答案
try:
方法不需要是全局的——它可以在任何范围内使用,因此模块可以在运行时“延迟加载”。例如:
def foo():
try:
import external_module
except ImportError:
external_module = None
if external_module:
external_module.some_whizzy_feature()
else:
print("You could be using a whizzy feature right now, if you had external_module.")
当您的脚本运行时,不会尝试加载 external_module
。第一次调用 foo()
时,external_module
(如果可用)被加载并插入到函数的本地范围中。随后对 foo()
的调用将 external_module
重新插入其范围,而无需重新加载模块。
一般来说,最好让 Python 处理导入逻辑——它已经这样做了一段时间。 :-)
关于python - 导入和提供可选功能的 Python 良好做法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/563022/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!