행위

파이썬 파일복사 자동스케줄러

DB CAFE

thumb_up 추천메뉴 바로가기



  1. 프로그램 설명
    1. C:\DEV에 있는 .torrent 파일을 D:\로 복사 하는 프로그램
    2. 프로그램을 트레이에 숨기는 기능
    3. .ini 파일에서 수정하는 항목
      1. 소스/타겟 디렉토리 수정
      2. 확장자명 수정
      3. 자동수행시간 간격(분)



import os

from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, QWidget, QCheckBox, QSystemTrayIcon, \
    QSpacerItem, QSizePolicy, QMenu, QAction, QStyle, qApp
from PyQt5.QtCore import QSize, QTime, QTimer
import logging
import shutil
import configparser

class MainWindow(QMainWindow):
    """
         Сheckbox and system tray icons.
         Will initialize in the constructor.
    """
    check_box = None
    tray_icon = None

    # Override the class constructor
    def __init__(self):
        try:
            # Be sure to call the super class method
            QMainWindow.__init__(self)

            self.config = self.getConfig()['DEFAULT']

            # 1분 마다 실행
            self.timer = QTimer(self)
            self.timer.start(1000 * 60 * int(self.config['SYNC_MIN']))    # 1/1000 * 60초 * 1 = 1분마다
            # self.timer.start(1000)    # 1/1000 * 60초 * 1 = 1분마다
            self.timer.timeout.connect(self.timeout_min)

            self.setMinimumSize(QSize(280, 80))  # Set sizes
            self.setWindowTitle("윈도우 자동 스케줄러")  # Set a title
            central_widget = QWidget(self)  # Create a central widget
            self.setCentralWidget(central_widget)  # Set the central widget

            grid_layout = QGridLayout(self)  # Create a QGridLayout
            central_widget.setLayout(grid_layout)  # Set the layout into the central widget
            grid_layout.addWidget(QLabel(" 파일 자동복사 스케줄러 ", self), 0, 0)

            # Add a checkbox, which will depend on the behavior of the program when the window is closed
            self.check_box = QCheckBox('트레이에 숨기기')
            grid_layout.addWidget(self.check_box, 1, 0)
            grid_layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding), 2, 0)

            # Init QSystemTrayIcon
            self.tray_icon = QSystemTrayIcon(self)
            self.tray_icon.setIcon(self.style().standardIcon(QStyle.SP_ComputerIcon))

            '''
                Define and add steps to work with the system tray icon
                show - show window
                hide - hide window
                exit - exit from application
            '''
            show_action = QAction("보이기", self)
            quit_action = QAction("Exit", self)
            hide_action = QAction("숨기기", self)
            show_action.triggered.connect(self.show)
            hide_action.triggered.connect(self.hide)
            quit_action.triggered.connect(qApp.quit)
            tray_menu = QMenu()
            tray_menu.addAction(show_action)
            tray_menu.addAction(hide_action)
            tray_menu.addAction(quit_action)
            self.tray_icon.setContextMenu(tray_menu)
            self.tray_icon.show()
        except Exception as e:
            l.info(e)


    def getConfig(self,inifile='cron_config.ini'):
        config = configparser.ConfigParser()
        config.read(inifile)

        return config




    # Override closeEvent, to intercept the window closing event
    # The window will be closed only if there is no check mark in the check box
    def closeEvent(self, event):
        if self.check_box.isChecked():
            event.ignore()
            self.hide()
            self.tray_icon.showMessage(
                "트레이 프로그램",
                "프로그램이 트레이에 최소화됩니다.",
                QSystemTrayIcon.Information,
                2000
            )

    ''' 시간별로 실행하는 스케줄러 '''
    def timeout_min(self):
        l.info(" Time  : " + QTime.currentTime().toString("hh:mm:ss"))
        _filelist = os.listdir(self.config['SRC_DIR'])

        for item in _filelist:
            # some_string 이 파일 이름에 없을 경우 -1 을 반환
            if item.find(self.config['SRC_FILE_EXT']) is not -1:
                l.info("item:" + item)
                shutil.move(self.config['SRC_DIR']+item,self.config['TGT_DIR'])

if __name__ == "__main__":
    import sys
    l = logging.getLogger("my")
    l.setLevel(logging.INFO)
    l.setLevel(logging.INFO)
    stream_hander = logging.StreamHandler()
    l.addHandler(stream_hander)
    l.info("==== started logging ====")

    app = QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec())
  1. 환경 파일(cron_config.ini)
[DEFAULT]
# 소스디렉토리
SRC_DIR = D:\\DEV\\ 
# 소스파일 확장자 
SRC_FILE_EXT = .torrent
# 타겟 디렉토리 
TGT_DIR = C:\\
# ?분마다 수행 
SYNC_MIN = 1