2012-12-15 97 views
1

我有多个机器上运行的python项目。我正在使用virtualenv跨多台机器同步python模块。这很好。不过,我正在将一些内部出售的SWIG * .so的软件包引入env中。这些C++共享对象具有一些深远的依赖性恶梦,这些恶梦很难在某些机器上重现。在一些开发机器上我不需要代码功能。我想不得不休息的Python代码加载,并继续摇摆不加修改。如何创建一个内嵌模块

我想在没有这些模块的机器上“伪装模块”加载。我不会调用实际执行SWIG * .so方法的代码。

例如:

try: 
    import swigpackagefoo.swigsubpackagebar 
except ImportError: 
    # magic code that defines the fake module, I want to define a bunch of class'es with 'pass' 
    # so all the code deps would be happy. and I dont require the swig *.so to 
    # be installed on the devel system. 
    # something along the lines of. 
    __import__('swigpackagefoo.swigsubpackagebar')=class foo(object): pass 

注:我认为它值得指出的是模块导入时,*。所以,督促机上 的

type(swigpackagefoo) 
# is 'module', also the 
type(swigpackagefoo.swigsubpackagebar) 
# is also 'module' 

所以“如何定义一个模块在线'在Python?

我不想对失踪devel的机器

创建包即:I DO-不想创建,因为在有效的系统模块冲突的这些文件。

$ tree 
    swigpackagefoo/__init__.py 
    swigpackagefoo/swigsubpackagebar/__init__.py 
+2

为什么你就不能'pass'您的例外条款吗?如果无论如何都不会使用这些模块,那么您甚至不需要名称空间中具有该名称的对象。另一种选择是填充与模块具有相同布局的类。 – mgilson

回答

2

如果我正确理解你,你希望能够“模拟”编译的模块,如果它不能被导入?

所以,如果在你的swigsubpackagebar您有:

swigsubpackagebar.aFunc(aString) -> outString 

然后你想一个“模拟”模块,支持相同的接口,但只是没有做任何事情。

,而不是试图与一些在即时模块定义解决这个问题,只是定义提供你想要的接口的另一模块:

## swigMock.py ## 
def aFunc(aString): 
    return aString 

然后组织你的导入声明是这样的:

## main.py ## 
try: 
    import swigpackagefoo.swigsubpackagebar as swigModule 
except ImportError: 
    import swigMock as swigModule 

print swigModule.aFunc("FOO") 

如果swigsubpackagebar实际上是一类,这几乎是同一个概念:

## swigMock.py ## 
class swigsubpackagebar(object): 
    pass 

而且再次使用as关键字命名它一样:

## main.py ## 
try: 
    import swigpackagefoo.swigsubpackagebar as swigClass 
except ImportError: 
    import swigMock.swigsubpackagebar as swigClass 

aClass = swigClass() 
+0

感谢'贾斯汀'我没有按照你的食谱为缺少的python模块创建模拟类。它工作的很好,对我来说是一个很好的方式来伪造特定方法调用的数据。 –