python application 시작에 해당하는 글 1

Python 개발시작 2일차

Study/Coding_Python|2019. 6. 20. 14:38
728x90
반응형

파이썬 개발공부를 시작한지 2일차.. 

 

오늘은 뭔가 업무가 많네요.ㅠㅠ 업무 처리하느라 틈틈히 개발 생각을 계속하면서 한줄 한줄 시작해 보고 있습니다. 

 

먼저 google calendar의 소스를 다운 받았어요. 

 

from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']

def main():
    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    # Call the Calendar API
    now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
    print('Getting the upcoming 10 events')
    events_result = service.events().list(calendarId='primary', timeMin=now,
                                        maxResults=10, singleEvents=True,
                                        orderBy='startTime').execute()
    events = events_result.get('items', [])

    if not events:
        print('No upcoming events found.')
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        print(start, event['summary'])

if __name__ == '__main__':
    main()
# [END calendar_quickstart]

 

 

위의 소스에 토큰은 없어서 일단 복사해보았습니다. 

 

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, qApp
from PyQt5.QtGui import QIcon



class MyApp(QMainWindow):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        exitAction = QAction(QIcon('exit.png'), 'Exit', self)   # 아이콘 exit.png와 'Exit' 라벨을 갖는 하나의 동작 action을 만듬
        exitAction.setShortcut('Ctrl+Q')                        # 단축키를 정할때 사용함
        exitAction.setStatusTip('Exit application')             # 상태바에 나타날 상태팁을 setStatusTip() 메서드를 사용하여 설정
        exitAction.triggered.connect(qApp.quit)                 # 동작을 선택했을때 QApplication위젯의 quit() 메서드에 연결 -> 종료

        self.statusBar()

        menubar = self.menuBar()
        menubar.setNativeMenuBar(False)
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)

        self.setWindowTitle("Hwan's Application")         # 메뉴툴바 타이틀
        self.move(300, 0)                                 # 위치를 나타냄 (x축, y축)
        self.resize(1500, 1000)                           # 위젯의 크기 단위는 px  
        self.show()                                       # 위젯을 스크린에 보여주는 것임 


    

if __name__ == '__main__':          # __name__ :현재 모듈의 이름이 저장되는 내장 변수 (만약 다른 모듈을 import해서 실행하면 name변수는 다른 모듈이 됨)

    app = QApplication(sys.argv)    # Application 객체생성     
    ex = MyApp()
    sys.exit(app.exec_())
    

 

제 소스는 이렇게 적어 나가고 있어요. 주석을 달면서 ㅎㅎ 뭔가 확실하게 한줄 한줄 알아야 할 것 같아서요. 

 

일단은 이렇게 시작하면서 python designer.exe.를 사용하지 않고, 직접 UI를 하나씩 짜보면서 문제마다 하나씩 해결해 봐야겠습니다. 

 

 

현재까지는 여기까지 진행되었습니다. 

너무 프로그래밍 못한다고 욕하시면 안되요!! ㅠㅠ

 

오늘 저녁에는 다른거라도 업데이트 시켜 나가야겠습니다. ㅎㅎ 

 

이상 투투아빠였습니다. ㅎ

728x90
반응형

댓글()