ABOUT ME

-

Today
-
Yesterday
-
Total
-
choco@desktop:~/tistory
$ 정보처리기사 요점정리
1과목 2과목 3과목 4과목 5과목 실기

$ Linux Kernel
Power Management DVFS
  • PyQt를 활용한 Python 명령어 실행 프로그램 만들기
    SW개발 2019. 3. 6. 23:09

    PyQt를 활용한 Python 명령어 실행 프로그램 만들기



    구현 목표


    Python Idle같은 프로그램을 구현해보고자 하였습니다. 아직은 초기 작업이고, 앞으로 수정해나가야 실제 IDLE와 비슷한 형태가 될 것입니다. 



    필요한 프로그램


    GUI 화면을 위해 사용한 프로그램은 Qt입니다. Qt를 Open source 버전으로 다운로드 받고, (https://www.qt.io/download) 튜토리얼을 따라서 원하는 UI 형태를 먼저 만듭니다. 화면 오른쪽 하단의 속성 목록들을 이용할 수도 있고, 마우스 오른쪽 버튼을 눌러서 CSS를 써서 속성을 변경할 수도 있습니다.


    파이썬에서 Qt와의 연결을 위해서 cmd 창에서 pip install PyQt5를 입력해서 설치를 했습니다. (반드시 관리자 권한으로 cmd 실행)



    Qt 로 UI 구현하기


    제목으로 사용한 부분과 결과를 출력할 부분 (속성 중 objectName은 Output_area로 설정해줌) 은 Label을 이용해서 만들었습니다. 명령어 Input을 받을 곳은 LineEdit 을 활용하여 만들었습니다. (속성 중 objectName은 Input_line으로 설정해줌) 참고한 튜토리얼은 https://opentutorials.org/module/544/9494 입니다.



    만든 UI

    my_python_ui.ui



    PyQt로 Qt UI와 연결하기


    파이썬 코드

    # my_python_repl.py

    import sys

    from PyQt5 import QtWidgets

    from PyQt5 import uic

    import subprocess

    import sys



    class Form(QtWidgets.QDialog):

        def __init__(self, parent=None):

            QtWidgets.QDialog.__init__(self, parent)

            self.ui = uic.loadUi("my_python_ui.ui")

            self.ui.Input_line.editingFinished.connect(self.proceed)

            self.ui.show()

            

        def keyPressEvent(self, e):

            if e.key() == Qt.key_Enter:

                self.proceed()

                

        def changeOutput(self, event):

            if event.key() == QtCore.Qt.Key_Enter:

                self.proceed()


        def proceed(self):

            proc = subprocess.Popen("""python -c """ + "%s > c:\\res.txt" % self.ui.Input_line.text(), stdout = subprocess.PIPE)

            output = proc.stdout.read().decode('ascii')

            self.ui.Output_area.setText(">> "+output)

        

    if __name__ == '__main__':

        app = QtWidgets.QApplication(sys.argv)

        w = Form()

        sys.exit(app.exec())



    결과물

    화면 모습




    보완할 점

    print('Hello') 는 가능하지만

    print("Hello") 처럼 큰 따옴표가 있거나 print('Hello Word") 처럼 띄어쓰기가 있는 경우, 1+2 같은 명령어는 실행이 안 된다.


    => interpreter와의 상호작용을 위한 모듈을 더 찾아봐야할 듯.


    Github 링크

    - ui 파일 (https://github.com/BY1994/TIL/blob/master/Python/SWdevelopment/my_python_ui.ui)

    - python 코드 (https://github.com/BY1994/TIL/blob/master/Python/SWdevelopment/my_python_repl.py)


    참고한 링크들


    # PyQt basic tutorial

    https://opentutorials.org/module/544/9494


    # name of Enter key

    https://stackoverflow.com/questions/38507011/implementing-keypressevent-in-qwidget


    # set Text (change label text)

    https://stackoverflow.com/questions/19985640/change-qlabel-text-dynamically-in-pyqt4


    # read Text

    https://stackoverflow.com/questions/3016974/how-to-get-text-in-qlineedit-when-qpushbutton-is-pressed-in-a-string


    # editing Finished

    https://www.tutorialspoint.com/pyqt/pyqt_qlineedit_widget.htm


    # button clicked connect

    https://www.pythonforengineers.com/your-first-gui-app-with-python-and-pyqt/



    반응형

    댓글

Designed by Tistory.