与修改后的 python 解释器的进程间通信

Interprocess communication with a modified python interpreter

TL;DR: 我如何生成不同的 python 解释器(从 python 内部)并在父子之间创建一个通信通道什么时候 stdin/stdout 不可用?


我希望我的 python 脚本执行 修改后的 python 解释器 并通过某种 IPC,例如 multiprocessing.Pipe 解释器运行的脚本。

假设我有类似于以下内容的内容:

subprocess.Popen(args=["/my_modified_python_interpreter.exe",
                       "--my_additional_flag",
                       "my_python_script.py"])

运行良好,执行我的 python 脚本和所有。

我现在想用修改后的 python 解释器设置某种 进程间通信

理想情况下,我想分享类似于 multiprocessing.Pipe() 的返回值之一的内容,但是我需要 分享 该对象与修改后的 python 过程(我怀疑 multiprocessing.Pipe 即使我这样做也处理不好)。

虽然发送文本和二进制文件就足够了(我不需要共享 python 对象或任何东西),但我确实需要它在所有主要操作系统上都能正常运行(windows,Linux, Mac).

更多use-case/business解释

更具体地说,修改后的解释器是 IDAPython interpreter that is shipped with IDA 以允许在 IDA 工具中编写脚本。

不幸的是,由于 stdio 已经大量用于现有的用户界面功能(由 IDA 提供),我无法使用 stdin/stdout 进行通信。


我正在寻找比我想象的更好的可能性:

  1. 使用两个(rx 和 tx 通道)硬盘文件并将路径作为参数传递给两者。
  2. 使用本地套接字并将路径作为参数传递。
  3. 在 windows 上使用内存映射文件和 tagname,在其他操作系统上使用其他一些同步方法。

在对 multiprocessing.Pipe function and the multiprocesing.Connection 对象进行一些修改后 returns,我意识到 Connection 对象的序列化比我原先想象的要简单得多。

一个Connection对象具有三个描述属性:

  1. fileno - 一个句柄。 Unix 上的任意文件描述符和 windows 上的套接字。
  2. readable - 控制是否可以读取 Connection 对象的布尔值。
  3. writable - 控制是否可以写入 Connection 对象的布尔值。

所有三个属性都可以作为对象属性访问,并且可以通过 Connection class 构造函数进行控制。

看来如果:

  1. 调用 Pipe 的进程生成一个子进程并共享 connection.fileno() 编号。
  2. 子进程使用该文件描述符作为句柄创建一个 Connection 对象。
  3. 两个解释器实现 Connection 对象大致相同(我猜这是有风险的部分)。

尽管这两个进程不共享相同的解释器构建并且多处理模块实际上并未用于实例化子进程,但可以在这两个进程之间 Connection.sendConnection.recv

编辑:

请注意 Connection class 在 python3 中作为 multiprocessing.connection.Connection 可用,在 python2 中作为 _multiprocessing.Connection 可用(可能建议不鼓励使用它。YMMV)

turned out to be a mistake. Because of how handles are inherited in python2 on Windows I couldn't get the same solution to work on Windows machines. I ended up using the far superior Listener and Client interfaces 一起出现在多处理模块中。

我的问题讨论了那个错误。