从python文件打印到kivy

时间:2019-01-12 06:35:59

标签: python-3.x kivy

假设我有一个python脚本名称myscript.py

import time
a = 0

def printing():
   global a
   a +=1
   print(" something = ", a)


if __name__ == "__main__":
   while True:
      time.sleep(1)
      printing()

如果我在python中运行此脚本,它将放出以下内容:

something = 1
something = 2 
something = 3 
...

我要寻找的是,如果我在kivy中按下开始按钮,它将启动myscript.py并在kivy GUI中打印出上面的消息。如果我按停止按钮,它将停止myscript.py

类似这样的东西: enter image description here

1 个答案:

答案 0 :(得分:1)

这是另一个可能的答案:

import time
from functools import partial
from threading import Thread

from kivy.app import App
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
import io
from contextlib import redirect_stdout

from myscript import printing

class MyLayout(BoxLayout):
    run_script = False

    def run_script_in_thread(self):
        self.the_thread = Thread(target=self.script, daemon=True).start()

    def script(self):
        self.run_script = True
        f = io.StringIO()
        with redirect_stdout(f):
            while self.run_script:
                time.sleep(1)
                printing()
                out = f.getvalue()
                Clock.schedule_once(partial(self.set_label, out), -1)

    def set_label(self, value, dt):
        self.ids.the_output.text = value

    def stop_script(self):
        self.run_script = False

theRoot = Builder.load_string('''
MyLayout:
    orientation: 'horizontal'
    Label:
        id: the_output
    Button:
        text: 'Start'
        on_release: root.run_script_in_thread()
    Button:
        text: 'Stop'
        on_release: root.stop_script()

''')

class MyApp(App):
    def build(self):
        return theRoot

if __name__ == '__main__':
    MyApp().run()

这使用redirect_stdout捕获来自printing()的输出,该输出是使用from myscript import printing导入的。请注意,while循环受if __name__ == "__main__":保护,因此无法使用。

如果您需要运行脚本,包括while循环,则可以使用单独的Process来运行它,并使用Pipe来捕获输出。