새소식

프로그래밍/Python

Python 잡동사니

  • -

1. keypress

#!python3
#-*- coding: utf-8 -*-

import ctypes
from time import sleep

USER32 = ctypes.windll.user32

KEY_DOWN = 0x00
KEY_ING = 0x01
KEY_UP = 0x02

BACKSPACE = 0x08
TAB = 0x09
ENTER = 0x0D
RIGHT_SHIFT = 0xA1
CTRL = 0x11
ALT = 0x12
ESC = 0x1B
PAGE_UP = 0x21
PAGE_DOWN = 0x22
END = 0x23
HOME = 0x24
LEFT_ARROW = 0x25
UP_ARROW = 0x26
RIGHT_ARROW = 0x27
DOWN_ARROW = 0x28
DELETE = 0x2E

NUM0 = 0x30
NUM1 = 0x31
NUM2 = 0x32
NUM3 = 0x33
NUM4 = 0x34
NUM5 = 0x35
NUM6 = 0x36
NUM7 = 0x37
NUM8 = 0x38
NUM9 = 0x39

F1 = 0x70
F2 = 0x71
F3 = 0x72
F4 = 0x73
F5 = 0x74
F6 = 0x75
F7 = 0x76
F8 = 0x77
F9 = 0x78
F10 = 0x79
F11 = 0x7A
F12 = 0x7B

KEY_A = 0x41
KEY_B = 0x42
KEY_C = 0x43
KEY_D = 0x44
KEY_E = 0x45
KEY_F = 0x46
KEY_G = 0x47
KEY_H = 0x48
KEY_I = 0x49
KEY_J = 0x4A
KEY_K = 0x4B
KEY_L = 0x4C
KEY_M = 0x4D
KEY_N = 0x4E
KEY_O = 0x4F
KEY_P = 0x50
KEY_Q = 0x51
KEY_R = 0x52
KEY_S = 0x53
KEY_T = 0x54
KEY_U = 0x55
KEY_V = 0x56
KEY_W = 0x57
KEY_X = 0x58
KEY_Y = 0x59
KEY_Z = 0x5A

def up_key(key_input):
    USER32.keybd_event(key_input, 0, KEY_UP, 0)
    sleep(0.1)

def down_key(key_input):
    USER32.keybd_event(key_input, 0, KEY_DOWN, 0)
    sleep(0.5)

def prees_key(key_input):
    down_key(key_input)
    sleep(0.3)
    up_key(key_input)
    
def double_up_key(first_key_input, second_key_input):
    USER32.keybd_event(first_key_input, 0, KEY_UP, 0)
    USER32.keybd_event(second_key_input, 0, KEY_UP, 0)
    sleep(0.1)
    
def double_down_key(first_key_input, second_key_input):
    USER32.keybd_event(first_key_input, 0, KEY_DOWN, 0)
    USER32.keybd_event(second_key_input, 0, KEY_DOWN, 0)
    sleep(0.1)

def double_press_key(first_key_input, second_key_input):
    USER32.keybd_event(first_key_input, 0, KEY_DOWN, 0)
    USER32.keybd_event(second_key_input, 0, KEY_DOWN, 0)
    sleep(0.5)   
    USER32.keybd_event(first_key_input, 0, KEY_UP, 0)
    USER32.keybd_event(second_key_input, 0, KEY_UP, 0)

def three_up_key(first_key_input, second_key_input, third_key_input):
    USER32.keybd_event(first_key_input, 0, KEY_UP, 0)
    USER32.keybd_event(second_key_input, 0, KEY_UP, 0)
    USER32.keybd_event(third_key_input, 0, KEY_UP, 0)
    sleep(0.1)

def three_down_key(first_key_input, second_key_input, third_key_input):
    USER32.keybd_event(first_key_input, 0, KEY_DOWN, 0)
    USER32.keybd_event(second_key_input, 0, KEY_DOWN, 0)
    USER32.keybd_event(third_key_input, 0, KEY_DOWN, 0)
    sleep(0.1)

def fast_down_key(key_input):
    USER32.keybd_event(key_input, 0, KEY_DOWN, 0)
    sleep(0.1)

 

 

2. message

import ctypes

"""Usage
import message
message.msgbox('내용','제목')
"""

def msgbox(text, title):
    MB_SYSTEMMODAL = 0x00001000
    MB_TOPMOST = 0x00040000
    ctypes.windll.user32.MessageBoxW(None, text, title, MB_SYSTEMMODAL | MB_TOPMOST)

 

 

3. util

# util : 문자열 복사 기능, 마우스 클릭 기능, 화면 제어 기능

import ctypes
import subprocess
from time import sleep
from ctypes import wintypes

user32 = ctypes.windll.user32
mouse = user32.mouse_event

MOUSE_LEFT_DOWN = 2
MOUSE_LEFT_UP = 4
MOUSE_RIGHT_DOWN = 8
MOUSE_RIGHT_UP = 16

WNDENUMPROC =ctypes.WINFUNCTYPE(
    wintypes.BOOL,
    wintypes.HWND,
    wintypes.LPARAM
)

def foreground_window(name):
    SW_RESTORE = 9
    
    def get_window_text(hwnd):
        length = user32.GetWindowTextLengthW(hwnd) + 1
        buffer = ctypes.create_unicode_buffer(length)
        user32.GetWindowTextW(hwnd, buffer, length)
        return buffer.value
    
    def proc(hwnd, _):
        if user32.IsWindowVisible(hwnd):
            if name in get_window_text(hwnd):
                if user32.IsIconic(hwnd):
                    user32.ShowWindow(hwnd, SW_RESTORE)
                user32.SetForegroundWindow(hwnd)
                return False
        return True
    return user32.EnumWindows(WNDENUMPROC(proc), None) == 0
    
def copy(string):
    subprocess.run(['clip.exe'], input=string.strip().encode('utf-16le'), check = True)

def click(down, up):
    mouse(down, 0, 0, 0, 0)
    mouse(up, 0, 0, 0, 0)

 

 

4. print_color

from colorama import init, Fore, Style

init()

# 주황색
def print_warn(*args, **kwargs):
    prefix = Fore.YELLOW + "[!]"
    suffix = Style.RESET_ALL
    print(prefix, *args, suffix, **kwargs)

# 초록색 
def print_info(*args, **kwargs):
    prefix = Fore.GREEN + "[!]"
    suffix = Style.RESET_ALL
    print(prefix, *args, suffix, **kwargs)

print_warn("작업종료 ({})".format("이것도 가능"))
print_warn("작업 종료")

print('')

print_info("작업종료 ({})".format("이것도 가능"))
print_info("작업 종료")

 

 

5. dtime

from datetime import datetime

# 현재 시간 구하기
now = datetime.now()

# 방법 1 - fstirng 이용
print(f"{now:%Y-%m-%d %H:%M:%S}")

# 방법 2 - format 이용
print("{}".format(now.strftime("%Y-%m-%d %H:%M:%S")))

# ===================================================
# 특정 시간을 더하거나, 특정 날짜 구하기
from datetime import datetime, timedelta

now = datetime.now()
delta = timedelta(days = 1)

time = (now + delta).strftime("%Y. %m. %d.")
print("1일 후 : " + time)

 

 

6. loop_test

#!python3
#-*- coding: utf-8 -*-

import ctypes
from os import system

from message import msgbox
from util import foreground_window
from loopTestException import *

__version__ = "2022.07.03"

class Loop:
    def __init__(self):
        self.select = 0
        print()
    
    def print_item(self, items):
        for item in items:
            print(item)
            
    def select_number(self, items, start=1):
        select_num = self.input_limit_check("==> 선택 : ", start, len(items))
        
        return select_num
    
    def input_limit_check(self, string, start, len_items):
        print(string, end='', flush=True)
        while True:
            try:
                num = int(input())
                if start <= num <= len_items:
                    return num
                else:
                    raise LimitInputNumber
            except LimitInputNumber:
                print("==> 선택 : ", end="")
    
    def show(self):
        print("\n[+] loopTestException\n")
        
        menu = (
            "1. 테스트다",
            "2. 두번째",
            "3. 테스트3"
        ) 
        
        self.print_item(menu)
        self.select = self.select_number(menu)

    def excute(self):
        if(self.select == 1):
            print("기능 테스트")
            
        elif(self.select == 2):
            print("기능 테스트 2")
        
        elif(self.select == 3):
            print("기능 테스트 3")

def init():
    ctypes.windll.kernel32.SetConsoleTitleW(f"loop Test v.{__version__}")
        
def main():
    loop = Loop()
    
    while True:
        loop.excute()
        loop.show()
        
if __name__ == '__main__':
    try:
        init()
        main()
    # ctrl + C 누른 경우
    except KeyboardInterrupt:
        pass
    finally:
        msgbox("~~~를 재실행 해주십시오.","알림")
        foreground_window("loopTest")
        system("pause")

 

 

7. loop_test_exception

#!python
# -*- coding: utf-8 -*-

class loopException(Exception):
    def __init__(self, *args):
        super().__init__(*args)
        print(*args)
    
class LimitInputNumber(loopException):
    def __init__(self):
        super().__init__("[!] 입력 범위를 초과했습니다.")

 

8. excel_test

import util
import kpress

tests = "t"
gests = "dassd"

# 쓸 일 없을 듯
def make_cell(lines):
    if not any(lines):
        return ""
    return '\r\n'.join(lines)

def make_row(*cells):
    return '\t'.join("{}".format(x) for x in cells)

def auto_diary_month():
    util.foreground_window("테스트")
    # 엑셀 화면이 존재하지 않을 경우
    #if not util.foreground_window("테스트"):
    #    raise WindowNotFoundError()

    kpress.double_press_key(kpress.CTRL, kpress.KEY_V)
    kpress.double_press_key(kpress.CTRL, kpress.RIGHT_ARROW)
    kpress.double_press_key(kpress.CTRL, kpress.LEFT_ARROW)
    kpress.prees_key(kpress.DOWN_ARROW)    

# 엑셀 행에 넣을 값
row = make_row(
    "내부망",
    "220607",
    tests,
    gests,
    "O"
)

util.copy(row)
auto_diary_month()

input()

'프로그래밍 > Python' 카테고리의 다른 글

Python JSON 파싱  (1) 2022.07.04
Python 명명 규칙  (0) 2022.07.04
보안뉴스 크롤러 제작 - 단순 출력  (0) 2020.07.17
파이썬 코딩 스타일  (0) 2020.07.16
모듈 설치 하는 방법  (0) 2020.07.16
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.