您的位置:首页 > 编程语言 > Python开发

用 pickle 实现简易“跨”Python实现平台的调用

2017-04-06 15:53 363 查看
有一次在用 Python 开发的时候遇到个问题:既需要调用 .Net Assembly,又需要调用只支持 CPythonmodule.

对于前一种场景,我们只能用 IronPython 作为引擎。

对于后一种场景,我们只能用 CPython。

 

当时找到一种简易的方法:遇到需要调用的模块不支持当前 Python 引擎时,让另一个 Python 引擎在独立的进程中执行目标方法,通过进程通信的方式传递参数及执行结果

 

为了降低进程通信时的复杂度,参数和执行结果在传递前都会先被序列化,另一进程收到信息后再反序列化。这就用到了 pickle。

 

上示例代码:

python_proxy.py:

 

import pickle

# Python 引擎
PYTHON = 'python'
IPY = 'ipy'

def invoke(driver, cmd_format, *args, **kwargs):
# 将参数序列化后保存到文件中
argFile = _dump((args, kwargs))

# 将存储参数的文件地址作为参数传给另一个 Python 引擎
from subprocess import Popen, PIPE
p = Popen([driver, '-c', cmd_format % argFile],
stdout = PIPE,
stderr = PIPE)
out, err = p.communicate()
if err:
raise AssertionError(err)

# 获取存有返回值的文件地址,读取内容,并反序列化得到最终结果
resultFile = out.strip()
result = _load(resultFile)

# 删除存储参数和反回值的临时文件
import os
os.remove(argFile)
os.remove(resultFile)

return result

def execute_with_file_arg(func, file):
# 读取文件内容,将其反序列化得到参数
args, kwargs = _load(file)

# 执行目标方法,并将序列化后的返回值存储到文件中,输出该文件地址
print _dump(func(*args, **kwargs))

def _load(file):
with open(file, 'rb') as f:
return pickle.load(f)

def _dump(o):
import tempfile
with tempfile.NamedTemporaryFile(delete = False) as f:
pickle.dump(o, f)
return f.name

 

test_module.py:

import python_proxy
import platform

current_driver = platform.python_implementation()

def func_common(num1, num2):
# 假设该方法核心代码必须在 IronPython 环境下执行

# 当前环境不是 IronPython:需要交给 IronPython 执行
if current_driver != 'IronPython':
return _func_for_non_ipy(num1, num2)

# 当前环境是 IronPython:直接运行核心代码并返回结果
return num1 + num2

def _func_for_non_ipy(num1, num2):
# 交给 IronPython 运行时所提供的命令格式
# 用参数文件地址格式化后可得到最终命令
cmd_format = 'import test_module; test_module.func_with_file_arg(r"%s")'
return python_proxy.invoke(python_proxy.IPY, cmd_format, num1, num2)

def func_with_file_arg(file):
python_proxy.execute_with_file_arg(func_common, file)

 

调用(是不是 IronPython 环境都可以):

 

import test_module
print test_module.func_common(1, 2)

 

该方法只是一个简易的取巧方法。

 

上述示例代码有一个很明显的弱点:如果在目标方法的核心代码中输出其它内容(如:在 'return num1 + num2' 前添加 'print "dummy message"'),将导致进程通信时拿到的输出信息包含这些内容,而不仅仅是我们想要的结果文件路径。

 

另外,该方法并不是真正的跨 Python 实现平台,只是在运行时调用其它 Python 平台来暂时替代。所以 IronPython 和 CPython 都得安装。而且如果有更多各种复杂的信息需要在两个 Python 平台之间共享(如:权限认证信息等),将会非常复杂。

Keep it simple, stupid!

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: