2012-12-18 3 views
2

학생용 파이썬 소스 코드를 등급 매기기위한 간단한 GUI가 시작됩니다. GUI 안에 파이썬 코드의 디스플레이를 자동으로 포맷하는 쉬운 방법이 있습니까? 예를 들어, 일부 편집기에서 색상 포맷을 가져 오는 중입니까?Python (또는 기타) GUI로 예쁜 파이썬 코드 표시

필자는 Python tkk로 시작했습니다. (약간의 파이썬 연습을하기 위해 가르쳐 봤지만 많이 사용하지는 않습니다.)이 부분에서 더 쉬운 언어라면 언어를 바꾸지 않습니다.

출력물에는 모든 성적 등이있는 웹 페이지가 있지만 Google Prettify를 사용하여 파이썬 코드가 표시됩니다 (누군가에게 더 좋은 제안이없는 한). 색 구성표를 유지할 필요가 없습니다. 채점이 더 쉬워진다.

감사합니다.

+3

내가 어떤 GUI 툴킷과 통합 생각하지 않지만, [Pygments (http://www.pygments.org/) 드릴 것입니다 당신은 소스 코드를 제공하고 색상을 가져옵니다. – icktoofay

+0

멋진데 도움이 될 것 같습니다! 나는 이러한 산출물로 확실히 일할 수 있습니다. 감사! – Meep

+1

나는 html을 렌더링 할 수 있다고 생각합니다. GUI 창에 쉽게 넣을 수 있습니다. –

답변

1

그냥 wxPython을이에 번들로 SciTe와 함께 제공 기억 :

#!/usr/bin/env python 

import wx 
from wx import stc 
import keyword 

class PyDialog(wx.Dialog): 
    def __init__(self): 
     wx.Dialog.__init__(self, None, -1, 'Python Code') 
     sizer = wx.BoxSizer(wx.VERTICAL) 

     self.stc = stc.StyledTextCtrl(self, -1) 
     self.stc.SetSizeHints(400, 400) 
     self.stc.SetLexer(stc.STC_LEX_PYTHON) 
     self.stc.SetKeyWords(0, " ".join(keyword.kwlist)) 
     self.stc.SetMarginType(1, stc.STC_MARGIN_NUMBER) 
     # Python styles 
     self.stc.StyleSetSpec(wx.stc.STC_P_DEFAULT, 'fore:#000000') 
     # Comments 
     self.stc.StyleSetSpec(wx.stc.STC_P_COMMENTLINE, 'fore:#008000,back:#F0FFF0') 
     self.stc.StyleSetSpec(wx.stc.STC_P_COMMENTBLOCK, 'fore:#008000,back:#F0FFF0') 
     # Numbers 
     self.stc.StyleSetSpec(wx.stc.STC_P_NUMBER, 'fore:#008080') 
     # Strings and characters 
     self.stc.StyleSetSpec(wx.stc.STC_P_STRING, 'fore:#800080') 
     self.stc.StyleSetSpec(wx.stc.STC_P_CHARACTER, 'fore:#800080') 
     # Keywords 
     self.stc.StyleSetSpec(wx.stc.STC_P_WORD, 'fore:#000080,bold') 
     # Triple quotes 
     self.stc.StyleSetSpec(wx.stc.STC_P_TRIPLE, 'fore:#800080,back:#FFFFEA') 
     self.stc.StyleSetSpec(wx.stc.STC_P_TRIPLEDOUBLE, 'fore:#800080,back:#FFFFEA') 
     # Class names 
     self.stc.StyleSetSpec(wx.stc.STC_P_CLASSNAME, 'fore:#0000FF,bold') 
     # Function names 
     self.stc.StyleSetSpec(wx.stc.STC_P_DEFNAME, 'fore:#008080,bold') 
     # Operators 
     self.stc.StyleSetSpec(wx.stc.STC_P_OPERATOR, 'fore:#800000,bold') 
     # Identifiers. I leave this as not bold because everything seems 
     # to be an identifier if it doesn't match the above criterae 
     self.stc.StyleSetSpec(wx.stc.STC_P_IDENTIFIER, 'fore:#000000') 

     # Caret color 
     self.stc.SetCaretForeground("BLUE") 
     # Selection background 
     self.stc.SetSelBackground(1, '#66CCFF') 

     sizer.Add(self.stc, 0, wx.EXPAND) 

     button = wx.Button(self, -1, 'Open...') 
     self.Bind(wx.EVT_BUTTON, self.OnOpen, button) 
     sizer.Add(button) 

     self.SetSizer(sizer) 
     sizer.Fit(self) 

    def OnOpen(self, evt): 
     dlg = wx.FileDialog(
      self, 
      message = 'Choose File', 
      wildcard = 'Python source (*.py)|*.py', 
      style = wx.OPEN) 

     if dlg.ShowModal() != wx.ID_OK: 
      return 

     with open(dlg.GetPath()) as fo: 
      self.stc.SetText(fo.read()) 

     dlg.Destroy() 


if __name__ == '__main__': 
    app = wx.PySimpleApp() 
    dlg = PyDialog() 
    with open(__file__) as fo: 
     dlg.stc.SetText(fo.read()) 
    dlg.ShowModal() 
+0

감사! 이것은 완벽하고 간단하며 구성 가능합니다. – Meep

1

@icktoofay가 말한 것처럼 Pygments를 사용할 수 있습니다. PyQt/PiSide, PyGtk 및 wxPython에는 모두 WebKit 위젯이 있습니다. (주 -하지 PyGtk의 전문가) 여기 PyGTK를 사용하는 예는 다음과 같습니다

#!/usr/bin/env python 
'''Example on using Pygments and gtk/webkit''' 

from pygments import highlight 
from pygments.lexers import PythonLexer 
from pygments.formatters import HtmlFormatter 

import gtk 
import webkit 

def gen_html(path): 
    '''Generate HTML for Python file with embedded CSS.''' 
    with open(path) as fo: 
     code = fo.read() 

    formatter = HtmlFormatter(linenos='table') 
    css = formatter.get_style_defs() 
    div = highlight(code, PythonLexer(), formatter) 

    return '''<html> 
     <head><style>{}</style></head> 
     <body><div>{}</div></body> 
     </html>'''.format(css, div) 

def get_file(): 
    '''Get file from user.''' 
    dlg = gtk.FileChooserDialog(
     title=None,action=gtk.FILE_CHOOSER_ACTION_OPEN, 
     buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK)) 
    dlg.set_default_response(gtk.RESPONSE_OK) 

    # Only Python files 
    filter = gtk.FileFilter() 
    filter.set_name("Python files") 
    filter.add_pattern("*.py") 
    dlg.add_filter(filter) 

    path = dlg.get_filename() if dlg.run() == gtk.RESPONSE_OK else None 
    dlg.destroy() 
    return path 

def load(view): 
    '''Load a new file''' 
    path = get_file() 
    if not path: 
     return 

    html = gen_html(path) 
    with open('/tmp/src.html', 'w') as fo: 
     fo.write(html) 
    view.load_html_string(html, '/') 


if __name__ == '__main__': 
    box = gtk.VBox() 
    # WebKit view in scroll 
    view = webkit.WebView() 
    sw = gtk.ScrolledWindow() 
    sw.add(view) 
    sw.set_size_request(600, 400) 
    box.pack_start(sw) 

    # Open file 
    btn = gtk.Button('Open...') 
    btn.connect('clicked', lambda e: load(view)) 
    box.pack_start(btn, False, False, 0) 

    # Quit 
    btn = gtk.Button('Quit') 
    btn.connect('clicked', lambda e: gtk.main_quit()) 
    box.pack_start(btn, False, False, 0) 

    # Main window 
    win = gtk.Window(gtk.WINDOW_TOPLEVEL) 
    win.add(box) 
    win.show_all() 

    gtk.main() 
1

ipython는 qt console 및 강조 지원하는 web server interface을 제공합니다. ipython 자체는 파이썬으로 쉽게 개발할 수있는 features을 많이 가지고 있습니다. ipython으로 모든 것을 얻으려면 엄청난 요구 사항 목록이 필요합니다. 대부분의 리눅스 배포판에는 패키지 관리 저장소에 ipython이 있으며 this site에서 사용할 수있는 Windows 설치 관리자가 있습니다.

bpython은 다른 python iterpreter 대체품입니다. 구문 강조, 인라인 도움말 및 기타 기능을 제공합니다. screenshots은 룩앤필에 대한 아이디어가있는 최고의 장소입니다. ipython보다 가볍습니다.

개인적으로 나는 html 노트북 서버를 설치하여 파이썬을 가르치기위한 실험실/교실의 일부로 사용했습니다.


질문의 다른 부분은 구문 강조 표시가있는 웹 페이지의 성적 표시입니다. 가장 쉬운 방법은 여러 가지 중 하나를 사용하는 것입니다. static site generators. 거의 모두 구문 강조 플러그인을 지원합니다.

+0

고마워요! 나는 ipython을 시험해 볼 것이지만, 내가 여기에서 원했던 것에 맞는지 확신 할 수 없다. Nanoc이 도움이 될 것입니다. – Meep