質問

を生み出しているプログラムを印刷結果ョンをインストールして下さい。(サーバーと版画のログインをョンをインストールして下さい。)

現在、私たい同じ結果を参照してくださいGUI.

たいのですがリダイレクトコマンドラインの結果をGUI?

ご提案フレキシビリティを簡単に変換コンソール-アプリケーションの簡単なGUI.

ように注意し、仕事はLinuxとWindowsの場合です。

役に立ちましたか?

解決

これで、テキストウィジェットのようなものに出力を追加し、サブプロセスとして、あなたのコマンドラインプログラムを実行するスクリプトラッパーを作成することができます。

from tkinter import *
import subprocess as sub
p = sub.Popen('./script',stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()

root = Tk()
text = Text(root)
text.pack()
text.insert(END, output)
root.mainloop()

スクリプトがあなたのプログラムです。あなたは明らかに異なる色、またはそのような何かのエラーを印刷することができます。

他のヒント

表示サブプロセスの出力にGUI の中で走る, ポータブル型stdlib-る唯一のソリューション作品の両方のPython2と3を使用しているが背景のスレッド:

#!/usr/bin/python
"""
- read output from a subprocess in a background thread
- show the output in the GUI
"""
import sys
from itertools import islice
from subprocess import Popen, PIPE
from textwrap import dedent
from threading import Thread

try:
    import Tkinter as tk
    from Queue import Queue, Empty
except ImportError:
    import tkinter as tk # Python 3
    from queue import Queue, Empty # Python 3

def iter_except(function, exception):
    """Works like builtin 2-argument `iter()`, but stops on `exception`."""
    try:
        while True:
            yield function()
    except exception:
        return

class DisplaySubprocessOutputDemo:
    def __init__(self, root):
        self.root = root

        # start dummy subprocess to generate some output
        self.process = Popen([sys.executable, "-u", "-c", dedent("""
            import itertools, time

            for i in itertools.count():
                print("%d.%d" % divmod(i, 10))
                time.sleep(0.1)
            """)], stdout=PIPE)

        # launch thread to read the subprocess output
        #   (put the subprocess output into the queue in a background thread,
        #    get output from the queue in the GUI thread.
        #    Output chain: process.readline -> queue -> label)
        q = Queue(maxsize=1024)  # limit output buffering (may stall subprocess)
        t = Thread(target=self.reader_thread, args=[q])
        t.daemon = True # close pipe if GUI process exits
        t.start()

        # show subprocess' stdout in GUI
        self.label = tk.Label(root, text="  ", font=(None, 200))
        self.label.pack(ipadx=4, padx=4, ipady=4, pady=4, fill='both')
        self.update(q) # start update loop

    def reader_thread(self, q):
        """Read subprocess output and put it into the queue."""
        try:
            with self.process.stdout as pipe:
                for line in iter(pipe.readline, b''):
                    q.put(line)
        finally:
            q.put(None)

    def update(self, q):
        """Update GUI with items from the queue."""
        for line in iter_except(q.get_nowait, Empty): # display all content
            if line is None:
                self.quit()
                return
            else:
                self.label['text'] = line # update GUI
                break # display no more than one line per 40 milliseconds
        self.root.after(40, self.update, q) # schedule next update

    def quit(self):
        self.process.kill() # exit subprocess if GUI is closed (zombie!)
        self.root.destroy()


root = tk.Tk()
app = DisplaySubprocessOutputDemo(root)
root.protocol("WM_DELETE_WINDOW", app.quit)
# center window
root.eval('tk::PlaceWindow %s center' % root.winfo_pathname(root.winfo_id()))
root.mainloop()

その解決には:

  • のサブプロセスの出力にはキューの背景のスレッド
  • の出力からキューのGUIスレです。

すなわち、 process.readline() を背景にスレッド->キュー->更新GUIのレーベルの主なねじになります。関連 kill-process.py (ポーリング--少ない移植性の高い解決法を使用する event_generate を背景にスしてはなりません。

サブプロセスを実行しているものの、おそらくよりエレガントなソリューションです -

あなたのGUIは行くための一つの方法である、そしておそらく最速の更新write()メソッドに標準出力をリダイレクトします。

あなたはそれが起動して作業だ本当に確信していたら、

のみ標準エラー出力をリダイレクトし、しかし!

例implimentation(GUIファイルとテストスクリプト)

test_gui.pyます:

from Tkinter import *
import sys
sys.path.append("/path/to/script/file/directory/")

class App(Frame):
    def run_script(self):
        sys.stdout = self
        ## sys.stderr = self
        try:
            del(sys.modules["test_script"])
        except:
            ## Yeah, it's a real ugly solution...
            pass
        import test_script
        test_script.HelloWorld()
        sys.stdout = sys.__stdout__
        ## sys.stderr = __stderr__

    def build_widgets(self):
        self.text1 = Text(self)
        self.text1.pack(side=TOP)
        self.button = Button(self)
        self.button["text"] = "Trigger script"
        self.button["command"] = self.run_script
        self.button.pack(side=TOP)

    def write(self, txt):
        self.text1.insert(INSERT, txt)

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.build_widgets()

root = Tk()
app = App(master = root)
app.mainloop()

test_script.pyます:

print "Hello world!"

def HelloWorld():
    print "HelloWorldFromDef!"

私の悪い英語のため申し訳ありません。私は実際に、私の新しいオートメーションツールにコマンドプロンプト出力を印刷する別の方法を使用していました。 以下、これらのステップを見つけるしてください。

1> batファイルを作成&LOGファイルに出力をリダイレクトします。 コマンドプロンプトコマンド:tasklist /svc

2>のPython 3.xではそのファイルを読みください `processedFile =オープン( 'D:\ LOG \ taskLog.txt'、 'R')

3>フィナーレ工程。 ttk.Label(Tab4, text=[ProcessFile.read()]).place(x=0, y=27)

**そこで私は、まだこのコードにスクロールバーが含まれていない、ということを知らされてください。

投稿スクリーンショットます:

" ここに画像の説明を入力する

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top