2013-06-11 2 views
4

소프트웨어를 개발 중이며 패키지 관리자와 같이 터미널에서 발생하는 출력을 표시하는 창이 필요합니다. 예를 들어, 내가 설치 명령을 내리는 경우, 설치 프로세스는 터미널이 아닌 내 창으로 부 터 outptutted되어야합니다. 파이썬 Gtk에서이 작업을 수행 할 수있는 방법이 있습니까?파이썬 Gtk를 사용하여 GUI 창에 터미널 출력 표시

+0

가 정확하려면, 우분투 13.04에서 작동합니다. –

+0

http://pygabriel.wordpress.com/2009/07/27/redirecting-the-stdout-on-a-gtk-textview/ –

답변

9

,이 같은 작업을해야합니다 :

import gtk 
import gobject 
import pango 
import os 
from subprocess import Popen, PIPE 
import fcntl 

wnd = gtk.Window() 
wnd.set_default_size(400, 400) 
wnd.connect("destroy", gtk.main_quit) 
textview = gtk.TextView() 
fontdesc = pango.FontDescription("monospace") 
textview.modify_font(fontdesc) 
scroll = gtk.ScrolledWindow() 
scroll.add(textview) 
exp = gtk.Expander("Details") 
exp.add(scroll) 
wnd.add(exp) 
wnd.show_all() 
sub_proc = Popen("ping -c 10 localhost", stdout=PIPE, shell=True) 
sub_outp = "" 


def non_block_read(output): 
    fd = output.fileno() 
    fl = fcntl.fcntl(fd, fcntl.F_GETFL) 
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) 
    try: 
     return output.read() 
    except: 
     return '' 


def update_terminal(): 
    textview.get_buffer().insert_at_cursor(non_block_read(sub_proc.stdout)) 
    return sub_proc.poll() is None 

gobject.timeout_add(100, update_terminal) 
gtk.main() 

블로킹이 아이디어는 here에서 읽기. 텍스트를 표시하는 라벨을 사용하여

:

import gtk 
import gobject 
import os 
from subprocess import Popen, PIPE 
import fcntl 

wnd = gtk.Window() 
wnd.set_default_size(400, 400) 
wnd.connect("destroy", gtk.main_quit) 
label = gtk.Label() 
label.set_alignment(0, 0) 
wnd.add(label) 
wnd.show_all() 
sub_proc = Popen("ping -c 10 localhost", stdout=PIPE, shell=True) 
sub_outp = "" 


def non_block_read(output): 
    ''' even in a thread, a normal read with block until the buffer is full ''' 
    fd = output.fileno() 
    fl = fcntl.fcntl(fd, fcntl.F_GETFL) 
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) 
    try: 
     return output.read() 
    except: 
     return '' 


def update_terminal(): 
    label.set_text(label.get_text() + non_block_read(sub_proc.stdout)) 
    return sub_proc.poll() is None 

gobject.timeout_add(100, update_terminal) 
gtk.main() 
+0

텍스트 뷰로 업데이트됩니다. 라벨로 보내고 싶다면? –

+0

텍스트 뷰가보기 흉한 것 같아 –

+0

레이블에 텍스트를 표시하는 코드가 추가되었습니다. – torfbolt

0

서브 프로세스 모듈과 os 모듈을 사용하여 터미널 출력을 가져올 수 있습니다.이 경우 question을 확인할 수 있습니다.

(당신이 상태로) 리눅스에있는 경우