Tkinter:无法通过subprocess.PIPE发送数据

时间:2017-08-05 04:36:41

标签: python tkinter subprocess pipe

我想发送&接收数据程序。没有数据发送到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"

1 个答案:

答案 0 :(得分:0)

我认为问题在于您尝试从receive.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() 获取数据。您的代码与下面显示的更改似乎对我有用。注意我清理了你的Tkinter GUI代码,只做了必要的事情。

sender.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

import UIKit



class WeatherCellLocationCell: UITableViewCell {

    @IBOutlet weak var localTime: UILabel!
    @IBOutlet weak var cityName: UILabel!
    @IBOutlet weak var currentTemp: UILabel!

    func configureCell(weatherPlace : WeatherPlaceData){

        localTime.text = DateFormatter.localizedString(from: weatherPlace.localDate, dateStyle: .none, timeStyle: .short)

        cityName.text = weatherPlace.name
        let temp = Int(weatherPlace.currentTemp)
        currentTemp.text = "\(temp)"

    }

    override func awakeFromNib() {
        super.awakeFromNib()


    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

    }

}