2012-01-04 6 views
2

모듈 가져 오기 예외를 처리하는 방법을 어디에서나 솔루션을 찾을 수 없습니다. '마법 부여'모듈을 가져와야하지만 먼저 설치되었는지 확인해야합니다. 설치되지 않았다면 오류 메시지를 표시해야합니다. 그래서 내가 이렇게하면 QMessageBox를 보여줄 방법이 없습니다. 메인 클래스가 아직 생성되지 않았기 때문입니다.PyQt - 모듈 가져 오기 예외를 처리하는 방법

import sys 
import re 

from PyQt4.QtCore import * 
from PyQt4.QtGui import * 

try: 
    import enchant 
    dict_list = enchant.list_languages() 
    if "ru_RU" in dict_list: 
     self.dict = enchant.Dict("ru_RU") 
    else: 
     self.dict = enchant.Dict() 
except ImportError, inst: 
    #How do I graphically show an error message here if the class hasn't been set up yet? 

class Translit(QMainWindow): 
    def __init__(self, parent = None): 
     super(Translit, self).__init__(parent) 

내가 할 경우이 :

import sys 
import re 

from PyQt4.QtCore import * 
from PyQt4.QtGui import * 

class Translit(QMainWindow): 
    def __init__(self, parent = None): 
     super(Translit, self).__init__(parent) 

    try: 
     import enchant 
     dict_list = enchant.list_languages() 
     if "ru_RU" in dict_list: 
      self.dict = enchant.Dict("ru_RU") 
     else: 
      self.dict = enchant.Dict() 
    except ImportError, inst: 
     QMessageBox.warning(parent, "", "Error:\n%s seems to be installed\n\nSpell checking will be disabled" % (inst)) 

    self.change_dict() 

    def change_dict(self): 
     self.dict = enchant.Dict("en_US") 
     QMessageBox.about(parent,"","Spellcheck is set to " + self.dict.tag) 

다음 인터프리터는 불평 "나가서 설명하자면 NameError : 전역 이름 '인챈트'가 정의되어 있지 않습니다."

모듈 가져 오기 예외 메시지를 표시하는 방법 또는 전체 프로그램에서 모듈을 작동시키는 방법을 알려주십시오. 고맙습니다. 사용자로, 맞춤법 검사는 옵션 기능이있는 경우,

from PyQt4.QtCore import * 
from PyQt4.QtGui import * 

try: 
    import enchant 
except ImportError: 
    enchant = None 

class Translit(QMainWindow): 
    def __init__(self, parent = None): 
     super(Translit, self).__init__(parent) 
     if enchant is not None: 
      dict_list = enchant.list_languages() 
      if "ru_RU" in dict_list: 
       self.dict = enchant.Dict("ru_RU") 
      else: 
       self.dict = enchant.Dict() 
      self.change_dict() 
     else: 
      self.dict = None 
      QMessageBox.warning(parent, "", 
       "Error: could not import the 'enchant' module\n\n" 
       "Spell checking will be disabled") 

    def change_dict(self): 
     if self.dict is not None: 
      self.dict = enchant.Dict("en_US") 
      QMessageBox.about(
       parent, "", "Spellcheck is set to " + self.dict.tag) 

그러나 :

__license__ = 'MIT' 
__copyright__ = '2009, John Schember ' 
__docformat__ = 'restructuredtext en' 

import re 
import sys 

import enchant 

from PyQt4.Qt import QAction 
from PyQt4.Qt import QApplication 
from PyQt4.Qt import QEvent 
from PyQt4.Qt import QMenu 
from PyQt4.Qt import QMouseEvent 
from PyQt4.Qt import QPlainTextEdit 
from PyQt4.Qt import QSyntaxHighlighter 
from PyQt4.Qt import QTextCharFormat 
from PyQt4.Qt import QTextCursor 
from PyQt4.Qt import Qt 
from PyQt4.QtCore import pyqtSignal 


class SpellTextEdit(QPlainTextEdit): 

def __init__(self, *args): 
    QPlainTextEdit.__init__(self, *args) 

    # Default dictionary based on the current locale. 
    self.dict = enchant.Dict("ru_RU") 
    self.highlighter = Highlighter(self.document()) 
    self.highlighter.setDict(self.dict) 

def mousePressEvent(self, event): 
    if event.button() == Qt.RightButton: 
     # Rewrite the mouse event to a left button event so the cursor is 
     # moved to the location of the pointer. 
     event = QMouseEvent(QEvent.MouseButtonPress, event.pos(), 
      Qt.LeftButton, Qt.LeftButton, Qt.NoModifier) 
    QPlainTextEdit.mousePressEvent(self, event) 

def contextMenuEvent(self, event): 
    popup_menu = self.createStandardContextMenu() 

    # Select the word under the cursor. 
    cursor = self.textCursor() 
    cursor.select(QTextCursor.WordUnderCursor) 
    self.setTextCursor(cursor) 

    # Check if the selected word is misspelled and offer spelling 
    # suggestions if it is. 
    if self.textCursor().hasSelection(): 
     text = unicode(self.textCursor().selectedText()) 
     if not self.dict.check(text): 
      spell_menu = QMenu('Spelling Suggestions') 
      for word in self.dict.suggest(text): 
       action = SpellAction(word, spell_menu) 
       action.correct.connect(self.correctWord) 
       spell_menu.addAction(action) 
      # Only add the spelling suggests to the menu if there are 
      # suggestions. 
      if len(spell_menu.actions()) != 0: 
       popup_menu.insertSeparator(popup_menu.actions()[0]) 
       popup_menu.insertMenu(popup_menu.actions()[0], spell_menu) 

    popup_menu.exec_(event.globalPos()) 

def correctWord(self, word): 
    ''' 
    Replaces the selected text with word. 
    ''' 
    cursor = self.textCursor() 
    cursor.beginEditBlock() 

    cursor.removeSelectedText() 
    cursor.insertText(word) 

    cursor.endEditBlock() 

class Highlighter(QSyntaxHighlighter): 

WORDS = u'(?iu)[\w\']+' 

def __init__(self, *args): 
    QSyntaxHighlighter.__init__(self, *args) 

    self.dict = None 

def setDict(self, dict): 
    self.dict = dict 

def highlightBlock(self, text): 
    if not self.dict: 
     return 

    text = unicode(text) 

    format = QTextCharFormat() 
    format.setUnderlineColor(Qt.red) 
    format.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline) 

    for word_object in re.finditer(self.WORDS, text): 
     if not self.dict.check(word_object.group()): 
      self.setFormat(word_object.start(), 
       word_object.end() - word_object.start(), format) 

class SpellAction(QAction): 

''' 
A special QAction that returns the text in a signal. 
''' 

correct = pyqtSignal(unicode) 

def __init__(self, *args): 
    QAction.__init__(self, *args) 

    self.triggered.connect(lambda x: self.correct.emit(
     unicode(self.text()))) 

def main(args=sys.argv): 
app = QApplication(args) 

spellEdit = SpellTextEdit() 
spellEdit.show() 

return app.exec_() 

if __name__ == '__main__': 
    sys.exit(main()) 
+0

해당 모듈없이 앱을 실행할 수 있습니까? 그렇지 않다면, 정규 예외로 스크립트를 종료하게하십시오. – Avaris

답변

1

여기에 귀하의 문제에 대한 하나의 가능한 수정의 :

는 여기에 재사용하기 위해 노력하고있어 원본 소스입니다 나는이 경고 메시지를 응용 프로그램을 실행할 때마다 받았을 때 나는 꽤 짜증이났다.

사용자가 맞춤법 검사기에 처음 액세스하려고 시도 할 때 경고를 표시 한 다음 더 이상 액세스하지 못하게하는 것이 좋습니다. 그러나이를 수행하는 방법은 분명히 enchant 모듈이 애플리케이션 내의 다른 곳에서 어떻게 사용되는지에 달려 있습니다.

+0

아, 저 아이디어가 마음에 들어요. 그러나 문제는 change_dict가 "NameError : global name 'enchant'가 정의되지 않았다는 것입니다. 이 글을 게시하자마자 매혹적인 클래스를 사용하는 방법을 보여준 튜토리얼 페이지가로드되면서 원하는 사전을 설정하는 데 사용할 수있는 중개인이 실제로 있습니다. – linuxoid

+0

@ user665327 가져 오기가 실패 할 경우'enchant'가 전역 적으로'None'으로 설정되기 때문에'NameError'를 지금 가져 오면 안됩니다. – ekhumoro

+0

고맙습니다. 그러나 또 다른 어리석은 질문. 나는 단추가 있는데, 눌렀을 때 철자가 켜져 있습니다. 하지만 다른 수업이 끝나면 어떻게 끌 수 있습니까? 버튼을 다시 누르면 클래스를 파기하고 다시 인스턴스화하는 것만 생각할 수 있습니다. 더 나은 해결책이 있습니까? 고맙습니다. – linuxoid