import logging
from datetime import datetime
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(message)s')
logging.debug('This is logging test')
logging.info('User see this')
logging.warning('Warning User')
logging.error('Error Occured')
logging.critical('Critical!')
# 터미널과 파일에 함께 로그 남기기
# 시간 [로그레벨] 메시지 형태로 로그 작성
logFormatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
logger = logging.getLogger()
# 로그 레벨 설정
logger.setLevel(logging.DEBUG)
# 스트림 (터미널)
streamHandler = logging.StreamHandler()
streamHandler.setFormatter(logFormatter)
logger.addHandler(streamHandler)
# 파일
filename = datetime.now().strftime('mylogfile_%Y%m%d%H%M%S.log') # mylogfile_20220221174212.log
fileHandler = logging.FileHandler(filename, encoding='utf-8')
fileHandler.setFormatter(logFormatter)
logger.addHandler(fileHandler)
logger.debug('testing')
2022-02-21 18:05:34,632 [DEBUG] This is logging test
2022-02-21 18:05:34,632 [INFO] User see this
2022-02-21 18:05:34,633 [WARNING] Warning User
2022-02-21 18:05:34,633 [ERROR] Error Occured
2022-02-21 18:05:34,633 [CRITICAL] Critical!
2022-02-21 18:05:34,633 [DEBUG] testing
2022-02-21 18:05:34,633 [DEBUG] testing
log level은 debug < info < warning < error < critical 순으로 커진다.
logging.basicConfig()의 level을 error로 하면 error 이상의 것(error, critical)만 log를 남긴다.
# 파일 기본
import os
print(os.getcwd()) # current working directory 현재 작업 공간
os.chdir('desktop_automation') # desktop_automation으로 작업 공간 이동
print(os.getcwd())
os.chdir('..') # 상위 디렉토리로 이동
print(os.getcwd())
os.chdir('../..') # 상위 디렉토리로 2번 이동
print(os.getcwd())
os.chdir(r'C:\Users\KrTeaparty\Desktop\study\Python_workspace\RPA') # 해당 절대 경로로 이동
print(os.getcwd())
# 파일 경로 만들기
file_path = os.path.join(os.getcwd(), 'my_file.txt') # 절대 경로 생성
print(file_path)
# 파일 경로에서 폴더 정보 가져오기
dname = os.path.dirname(r'C:\Users\KrTeaparty\Desktop\study\Python_workspace\RPA\my_file.txt')
print(dname)
# 파일 정보 가져오기
import time
import datetime
# 파일의 생성 날짜
ctime = os.path.getctime('desktop_automation/11_file_system.py')
print(ctime)
# 날짜 정보를 strftime을 통해서 연월일 시분초 형태로 출력
print(datetime.datetime.fromtimestamp(ctime).strftime('%Y%m%d %H:%M:%S'))
# 파일의 수정 날짜
mtime = os.path.getmtime('desktop_automation/11_file_system.py')
print(datetime.datetime.fromtimestamp(mtime).strftime('%Y%m%d %H:%M:%S'))
# 파일의 마지막 접근 날짜
atime = os.path.getatime('desktop_automation/11_file_system.py')
print(datetime.datetime.fromtimestamp(atime).strftime('%Y%m%d %H:%M:%S'))
# 파일 크기
size = os.path.getsize('desktop_automation/11_file_system.py') # 바이트 단위로 파일크기를 가져옴
print(size)
C:\Users\KrTeaparty\Desktop\study\Python_workspace\RPA
C:\Users\KrTeaparty\Desktop\study\Python_workspace\RPA\desktop_automation
C:\Users\KrTeaparty\Desktop\study\Python_workspace\RPA
C:\Users\KrTeaparty\Desktop\study
C:\Users\KrTeaparty\Desktop\study\Python_workspace\RPA
C:\Users\KrTeaparty\Desktop\study\Python_workspace\RPA\my_file.txt
C:\Users\KrTeaparty\Desktop\study\Python_workspace\RPA
1645433133.7375057
20220221 17:45:33
20220221 18:02:19
20220221 18:02:19
1529
# 파일 목록 가져오기
print(os.listdir()) # 모든 폴더, 파일 목록 가져오기
print(os.listdir('desktop_automation')) # 주어진 폴더 밑에서 모든 폴더, 파일 목록 가져오기
# 파일 목록 가져오기 (하위 폴더 포함)
result = os.walk('.')
print(result)
for root, dirs, files in result:
print(root, dirs, files)
# 폴더 내에서 특정 파일들을 찾기
name = '11_file_system.py'
result = []
for root, dirs, files in os.walk('.'):
if name in files:
result.append(os.path.join(root, name))
print(result)
['desktop_automation', 'excel_automation']
['10_log.py', '11_file_system.py', '1_env.py', '2_mouse_move.py', '3_mouse_action.py', '4_mouse_info.py', '5_screen.py', '6_image_recognition.py', '7_window.py', '8_keyboard.py', '9_message_box.py', 'checkbox.PNG', 'desktop_output', 'file_menu.png']
<generator object walk at 0x0000015F6C45E0B0>
. ['desktop_automation', 'excel_automation'] []
.\desktop_automation ['desktop_output'] ['10_log.py', '11_file_system.py', '1_env.py', '2_mouse_move.py', '3_mouse_action.py', '4_mouse_info.py', '5_screen.py', '6_image_recognition.py', '7_window.py', '8_keyboard.py', '9_message_box.py', 'checkbox.PNG', 'file_menu.png']
.\desktop_automation\desktop_output [] ['mouse_info.PNG']
.\excel_automation ['excel_output'] ['10_chart.py', '11_cell_style.py', '12_formula.py', '13_formula_dataonly.py', '14_merge.py', '15_unmerge.py', '16_image.py', '17_quiz.py', '1_create_file.py', '2_sheet.py', '3_cell.py', '4_open_file.py', '5_cell_range.py', '6_search.py', '7_insert.py', '8_delete.py', '9_move.py', 'aurora.jpg']
.\excel_automation\excel_output [] ['10_1.PNG', '10_2.PNG', '11_1.PNG', '11_2.PNG', '12.PNG', '14.PNG', '15.PNG', '16.PNG', '1_.PNG', '2_.PNG', '3_.PNG', '5_.PNG', '5_1.PNG', '6_.PNG', '7_1.PNG', '7_2.PNG', '8_1.PNG', '8_2.PNG', '9_1.PNG', 'quiz.PNG', 'quiz_1.PNG']
['.\desktop_automation\11_file_system.py']
walk generator는 3개의 값을 가진 튜플을 반환해주는데, (root 폴더, 하위 폴더들, 하위의 모든 파일)로 구성된다.
walk의 결과를 해석해보겠다.
. ['desktop_automation', 'excel_automation'] []
.\desktop_automation ['desktop_output'] ['10_log.py', '11_file_system.py', '1_env.py', '2_mouse_move.py', '3_mouse_action.py', '4_mouse_info.py', '5_screen.py', '6_image_recognition.py', '7_window.py', '8_keyboard.py', '9_message_box.py', 'checkbox.PNG', 'file_menu.png']
.\desktop_automation\desktop_output [] ['mouse_info.PNG']
'.'에서는 root가 '.', 디렉토리가 2개, 파일은 없다. 그 다음에 하위 디렉토리인 desktop_automation으로 내려갔으니 root는 '.\desktop_automation'이 되고 하위 디렉토리는 1개, 그 다음은 파일들이다. 이런식으로 반복이 된다.
# 폴더 내에서 특정 패턴을 가진 파일 찾기
import fnmatch
pattern = '*.png' # .py로 끝나는 모든 파일
result = []
for root, dirs, files in os.walk('.'):
for file in files:
if fnmatch.fnmatch(name, pattern): # 이름이 패턴과 일치하면
result.append(os.path.join(root, name))
print(result)
['.\desktop_automation\checkbox.PNG', '.\desktop_automation\file_menu.png', '.\desktop_automation\desktop_output\mouse_info.PNG', '.\excel_automation\excel_output\10_1.PNG', '.\excel_automation\excel_output\10_2.PNG', '.\excel_automation\excel_output\11_1.PNG', '.\excel_automation\excel_output\11_2.PNG', '.\excel_automation\excel_output\12.PNG', '.\excel_automation\excel_output\14.PNG', '.\excel_automation\excel_output\15.PNG', '.\excel_automation\excel_output\16.PNG', '.\excel_automation\excel_output\1_.PNG', '.\excel_automation\excel_output\2_.PNG', '.\excel_automation\excel_output\3_.PNG', '.\excel_automation\excel_output\5_.PNG', '.\excel_automation\excel_output\5_1.PNG', '.\excel_automation\excel_output\6_.PNG', '.\excel_automation\excel_output\7_1.PNG', '.\excel_automation\excel_output\7_2.PNG', '.\excel_automation\excel_output\8_1.PNG', '.\excel_automation\excel_output\8_2.PNG', '.\excel_automation\excel_output\9_1.PNG', '.\excel_automation\excel_output\quiz.PNG', '.\excel_automation\excel_output\quiz_1.PNG']
# 주어진 경로가 파일인지 폴더인지 확인
print(os.path.isdir('dektop_automation')) # 폴더인지 확인
print(os.path.isfile('desktop_automation')) # 파일인지 확인
# 주어진 경로가 존재하는지 확인
if os.path.exists('desktop_automation'):
print('exist')
else:
print('not exist')
# 파일 만들기
open('new_file.txt', 'a').close() # 빈 파일 생성
# 파일명(폴더명) 변경하기
os.rename('new_file.txt', 'new_file_rename.txt')
# 파일 삭제하기
os.remove('new_file_rename.txt')
# 폴더 만들기
os.mkdir('new_dir')
# 하위 폴더를 가지는 폴더 생성
os.mkdirs('new_dir2/a/b/c')
# 폴더 지우기
os.rmdir('new_dir') # 폴더 안이 비었을 때만 삭제 가능
import shutil # shell utilities
shutil.rmtree('new_dir2') # 폴더 안이 비어있지 않아도 완전 삭제 가능
isdir과 isfile은 해당 경로에 해당하는 파일이나 폴더가 없다면 False를 반환한다.
mkdir로 이미 있는 이름의 디렉토리를 만들려고 하면 에러가 발생한다.
# 파일 복사하기
# 어떤 파일을 폴더 안으로 복사
shutil.copy('checkbox.png', 'desktop_automation') # 원본 경로, 대상 경로
# 어떤 파일을 폴더 안에 새로운 파일 이름으로 복사
shutil.copy('checkbox.png', 'desktop_automation/copied.png')
shutil.copyfile('checkbox.png', 'dektop_automation/chkbox.png') # 원본 파일 경로, 대상 파일 경로
shutil.copy2('checkbox.png', 'dektop_automation/copy2.png')
# 폴더 복사
shutil.copytree('test', 'test2') # 원본 폴더 경로, 대상 폴더 경로
# 폴더 이동
shutil.move('test', 'test2') # test 폴더가 test2 아래로 이동한다.
copyfile은 파일 경로가 아닌 디렉토리를 주면 에러가 발생한다.
copy와 copyfile은 메타정보를 복사하지 않지만 copy2는 메타정보를 복사한다.
수행할 행동
- 그림판 실행 (win + r, mspaint 입력) 및 최대화
- 상단의 텍스트 기능을 이용하여 흰 영역 아무 곳에다가 글자 입력
- 텍스트 : "참 잘했어요"
- 5초 대기 후 그림판 종료 (저장하지 않음을 자동으로 선택하여 완전 종료)
import pyautogui
import sys
import pyperclip
pyautogui.PAUSE = 0.5 # 각 행동 사이에 0.5초의 sleep 적용
# 그림판 켜기
pyautogui.hotkey('win', 'r')
pyautogui.write('mspaint')
pyautogui.press('enter')
pyautogui.sleep(2)
painter = pyautogui.getActiveWindow()
# 최대화
if painter.isMaximized == False:
painter.maximize()
# 텍스트 기능 찾아서 클릭
text_btn = pyautogui.locateOnScreen('./desktop_automation/text.png')
if text_btn:
pyautogui.click(text_btn)
else:
print('Not Found')
sys.exit()
# 흰 영역 아무 곳에다가 글자 입력
pyautogui.moveTo(300, 300)
pyautogui.click()
pyperclip.copy('참 잘했어요')
pyautogui.hotkey('ctrl', 'v')
pyautogui.move(-50, -50)
pyautogui.click()
pyautogui.sleep(5)
# 그림판 종료 및 저장하지 않음
painter.close()
pyautogui.press('n')