python - 在“with”语句中提取代码并将其从运行时中删除
问题描述
上下文
我正在尝试创建一个“环境”上下文管理器。可以将其视为根据上下文管理器的参数选择在本地或远程执行某些代码:
with PythonExecutor(env="local"):
x = 1
assert x == 1
将在进程中运行该代码。但是,将env
参数更改为"remote"
将连接到 SSH 并远程执行代码。
感谢这个 StackOverflow question,我设法将with
块中的代码提取为方法中的字符串,__exit__
并且 SSH 部分是微不足道的(与该问题无关)。
问题
如何防止with
块内的代码在进程内运行?上下文管理器始终遵循:
- 打电话
__enter__
with
在块内执行代码- 打电话
__exit__
这意味着即使我选择"remote"
执行,代码也会在__enter__
or中远程执行__exit__
,但还是会在本地执行。换句话说,有没有办法跳过第 2 步?我开始研究运行时字节码操作,但它变得有点毛茸茸……</p>
也欢迎原始问题的其他解决方案(以优雅的方式在不同环境中运行代码)
解决方案
这有点 hacky,需要稍微更改 with 块的代码,但是您可以让您的__enter__
方法返回一个在env == 'remote'
. 然后在远程情况下,您将收到本地错误,然后处理__exit__
块中的所有其他内容。
class PythonExecutor:
def __init__(self, env):
self.env = env
def __enter__(self):
def switch():
if self.env == 'remote':
raise Exception # Probably some custom exception for only this purpose
return switch
def __exit__(self, exctype, excinst, exctb):
# do ssh stuff here depending on exctype
...
with PythonExecutor(env='remote') as switch:
switch()
print('hello')
推荐阅读
- android - 当用户点击firebase通知时,重定向的最佳方式是什么?
- vue.js - 当前输入更改的 VeeValidate 3 setErrors 错误消息
- excel - 如何从另一个 Excel 工作簿复制单元格值?
- phrets - 使用 PHRETS v2,我可以按字母顺序对数据字段进行排序吗?(使用V1时有这个)
- python - 如何在python(pandas kde)中提取密度函数概率
- ajax - 为什么 Docusign 身份验证需要重定向 URL ?? 我们可以在没有重定向 URL 的情况下验证 API 吗?
- j8583 - 解析某些 ISO8583 字段时出错
- javascript - 如何以简单的方式为我的函数分配从 php 调用到 Javascript 的增值税值?
- html - 无法在网格的正确单元格中定位元素
- go - 创建系统以动态加载和卸载共享对象作为插件