Python3子进程通信示例

2022-01-18 00:00:00 python subprocess pipe communicate

问题描述

我是子处理的新手.

我只需要一个在 parent.py 和 child.py 之间进行通信的非常简单的 win32 示例.从 parent.py 发送到 child.py 的字符串,由 child.py 更改并从 parent.py 发送回 parent.py 以进行 print().

我发布这个是因为我发现的示例最终不是 win32 或者没有使用让我感到困惑的孩子.

I just need a really simple win32 example of communicate() between a parent.py and child.py. A string sent from parent.py to child.py, altered by child.py and sent back to parent.py for print() from parent.py.

I'm posting this because examples I have found end up either not being win32 or not using a child which just confuses me.

感谢您的帮助.


解决方案

这里是根据您的要求的一个简单示例.此示例是 Python 3.x(2.x 需要稍作修改).

Here is a simple example as per your requirements. This example is Python 3.x (slight modifications are required for 2.x).

import subprocess
import sys

s = "test"
p = subprocess.Popen([sys.executable, "child.py"],
                     stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE)
out, _ = p.communicate(s.encode())
print(out.decode())

child.py

s = input()
s = s.upper()
print(s)

我在 Mac OS X 上编写并测试了它.这里没有特定于平台的代码,所以没有理由它也不能在 Win32 上运行.

I wrote and tested this on Mac OS X. There is no platform-specific code here, so there is no reason why it won't work on Win32 also.

相关文章