【问题标题】:Tkinter: Unable to send data via subprocess.PIPETkinter:无法通过 subprocess.PIPE 发送数据
【发布时间】:2017-08-05 04:36:40
【问题描述】:

我想做发送和接收数据程序。没有数据发送到receive.py,当我关闭 tkinter GUI 时,我得到一个空列表。

sender.py

import Tkinter as tk
import sys

def send(x):
    sys.stdout.write(x)
    return sys.stdout.flush()

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        x = ''.join(str(self.entry.get()))
        return send(x)

app = SampleApp()
app.mainloop()

receive.py

import subprocess
import time

xx = subprocess.Popen(["python","sender.py"], stdout=subprocess.PIPE,
                      stdin=subprocess.PIPE, shell=True)

while True:
    time.sleep(0.5)
    if xx.stdout.readlines():
        print xx.stdout.readlines()
    else:
        print "wait data"

【问题讨论】:

  • 你如何开始你的程序?它们需要连接在“管道”中才能使管道转发工作。
  • 另请注意,在receive.py 第一次调用xx.stdout.readlines() 时,它会读取所有行,因此第二次调用时不会剩下任何行。
  • piiipe.py 是什么?
  • @martineau piiipe.py == sender.py
  • @martineau 将 xx.stdout.readlines() 更改为 xx.stdout.readline() 没有任何反应

标签: python tkinter subprocess pipe


【解决方案1】:

我认为问题在于您尝试从sender.py 中的receive.py 取回数据的方式。您的代码与下面显示的更改似乎对我有用。注意我清理了你的 Tkinter GUI 代码,只做必要的事情。

sender.py

import Tkinter as tk
import sys

def send(x):
    sys.stdout.write(x)
    sys.stdout.flush()

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.entry.pack()
        self.entry.focus_set()  # added (optional)

    def on_button(self):
        x = ''.join(str(self.entry.get()))
        send(x)

app = SampleApp()
app.mainloop()

receive.py

import subprocess

with subprocess.Popen(["python","sender.py"], stdout=subprocess.PIPE,
                      stderr=subprocess.STDOUT, stdin=subprocess.PIPE,
                      shell=True).stdout as output:
    for line in output:
        print(line)

【讨论】:

  • 没有数据发送到receive.py我应该关闭gui来接收数据
  • fadymalak:在 GUI 关闭之前我也看不到任何输出。我怀疑这与 Tkinter mainloop() 有关。它也可能是特定于操作系统的。我正在运行 Windows。如果不是,请尝试删除 shell=True 关键字参数。
  • fadymalak:如果您使用multiprocessing 模块和multiprocessing.Queue 而不是subprocesssubprocess.PIPE 将数据从发送方发送到接收方,这可能会更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 2013-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-16
  • 2015-02-13
相关资源
最近更新 更多