如何在两个正在运行的python程序之间交换字符串?

时间:2019-01-05 17:26:08

标签: python string subprocess python-imaging-library

我想通过使用字符串将python程序生成的图像交换到另一个正在运行的python程序。

(我必须使用字符串,因为在实际应用程序中,字符串来自C程序而不是python程序,但这没关系)

因此,使用一个程序,我必须阅读控制台上打印的其他程序。

但是像我现在做的那样,它不起作用,当我并行运行两个程序时,图像无法正确传输,图像只是灰色,因此读取器字符串与打印的字符串不同。 / p>

我的错误在哪里?

发件人计划:

import time
from PIL import Image
import sys

image = Image.open("t.png")

while True:
    print(image.tobytes())
    time.sleep(5)

接收器程序:

import os
import sys
from PIL import Image
from subprocess import Popen, PIPE, STDOUT

script_path = os.path.join('lsend.py')

p = Popen([sys.executable, '-u', script_path],
          stdout=PIPE, stderr=STDOUT, bufsize=1)

while True:
    string = p.stdout.readline()
    print("image received !!!")
    print(string[0:10])
    try:
        image = Image.frombytes('RGBA',(90, 36),string,"raw")
        image.show()
    except:
        print("fail")

我的图片:

my test image

感谢您的回答!

2 个答案:

答案 0 :(得分:1)

我认为您的代码有两个问题:

  • 没有消息边界-发送方仅发送连续的字节流,而接收方不知道一个图像在哪里结束,下一幅图像在哪里开始,

  • Image.tobytes()似乎想与Image.frombuffer()而不是Image.frombytes()配对-不知道为什么!

因此,我让您的发送者只发送单个图像,而您的接收者仅接收单个图像。我猜您可能想在上面写一些协议来说明即将到来的字节数,然后接收器将在收到一个图像后停止并开始等待新的字节数。

这里是lsend.py

#!/usr/bin/env python3

import sys
from PIL import Image

image = Image.open('lora.png').convert('RGB')
sys.stdout.buffer.write(image.tobytes())

这是receiver.py

#!/usr/bin/env python3

import os
import sys
from PIL import Image
from subprocess import Popen, PIPE, STDOUT, DEVNULL

process = Popen(['./lsend.py'], stdout=PIPE, stderr=DEVNULL)
stdout, _ = process.communicate()

try:
   image = Image.frombuffer('RGB',(90,36),stdout)
   image.show()
except:
   print("fail")

答案 1 :(得分:0)

如果最终结果是要传输视频,我建议使用套接字。

Python应该在socket库中提供您所需的一切

这应该大致了解如何通过套接字发送数据:

sender.py

import socket

# Host the socket on localhost for this example.
# This could send over a network too though.
host = "0.0.0.0"
port = 8000

# Initialize the socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))

# The number of connections to listen for.
sock.listen(5)
print("Server listening.")

while True:

    try:
        # Accept an incoming connection from the client.
        client, addr = sock.accept()
        print("Accepted connection from client.")

        # Wait until the client sends data.
        data = client.recv(1024)
        print(data)

        # Send some data back to the client.
        s = "Hello client"
        client.send(s.encode())

        client.close()

    except KeyboardInterrupt:
        break

连接到套接字类似于托管它。无需呼叫socket.bind,只需呼叫socket.connect,然后删除socket.listen

receiver.py

import socket

# The host and port the socket is hosted on.
host = "0.0.0.0"
port = 8000

# Create the socket and connect to the server.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))

# Send the server some data.
s = "Hello server"
sock.send(s.encode())

# And receive some back.
data = sock.recv(1024)
print(data)