我管理着一个相当大的基于python的量子化学套件PyQuante。我目前正在努力解决如何设置各种默认值,以便用户可以在运行时选择不同的选项。
例如,我有三种不同的方法来计算电子排斥积分。让我们称它们为a,b,c。我过去只是简单地选择我最喜欢的(比如c),并将其硬连接到计算这些积分的模块中。
我现在已经将其修改为使用一个模块Defaults.py,该模块包含所有这样的硬连接。但这是在编译/安装时设置的。我现在希望用户能够在运行时覆盖这些选项,比如使用.pyquanterc.py文件。
在我的积分例程中,我目前有这样的东西
from Defaults import integral_method
我知道字典和.update()方法。但我不知道如何在现实生活中使用它。我的默认模块看起来像这样
integral_method = c
我是否应该修改Defaults.py的末尾以查找.pythonrc.py文件并覆盖这些值?例如。
if os.path.exists('$HOME/.pythonrc.py'): do_something
如果是这样,do_something应该是什么样子的?
发布于 2011-05-26 22:56:19
使用您当前的设置,用户可以很容易地更改其脚本中的默认函数:
import Defaults
Defaults.integral_method = somefunc
如果用户将此代码添加到他的脚本中,那么所有使用来自Defaults
的integral_method
的模块都将使用somefunc
来计算积分。
发布于 2011-05-26 22:57:32
我可能会通过一个工厂类来做这件事。
class IntegralSolver:
"""
Factory class containing methods for solving integrals.
>>> solver = IntegralSolver("method1")
>>> solver(x)
# solution via method1
Can also be used directly:
>>> IntegralSolver.method2(x)
# solution via method2
"""
def __init__(self, method):
self.__call__ = getattr(self, method)
@staticmethod
def method1(x):
return method1_solution
@staticmethod
def method2(x):
return method2_solution
发布于 2011-05-26 23:02:42
这真的取决于你的用户如何运行工具集。如果他们每次都旋转python代码,那么只需在顶部设置一个标记为OPTIONS的块就可以了。如果他们从命令行运行,请使用argparse库来允许他们在命令行上切换选项。也许让它使用configParser从文件中读取选项,以读取包含您的选项的默认文件,如果用户设置了选项,则读取包含其选项的附加文件。
https://stackoverflow.com/questions/6140542
复制相似问题