2018-09-19
최근 파이썬 공부를 다시 하고 있다.
공부하면서, 유용해 보이거나, 내가 까먹기 쉬워보이는 것들은 여기에 저장해놓을 생각이다.
모듈 설치
C:\>pip install pyautogui
Collecting pyautogui
  Downloading https://files.pythonhosted.org/packages/69/81/a8f44c4b613717c25e0c
dabf405e942fc7c7bcedf3198c58c79fdbababc0/PyAutoGUI-0.9.38.tar.gz (47kB)
    100% |████████████████████████████████| 51kB 632kB/s
Collecting pymsgbox (from pyautogui)
.
.
.
pyautogui 모듈 설치예시
for문
>>> dic = {'a':1, 'b':2, 'c':3}
>>> for i,j in dic.items():
	print(i, j)

a 1
b 2
c 3
>>> # for i in dic.values():
>>> for i in dic.keys():
	print(i)

a
b
c
>>> # 경로 뽑아낼때
>>> for x in os.listdir('C:\ProgramData\Anaconda3'):
        if x.endswith('exe'):
                print(x)
openssl.exe
python.exe
pythonw.exe
Uninstall-Anaconda3.exe
>>> # 인덱스 같이 뽑아낼때
>>> for i, j in enumerate(['a','b','c']):
	 print(i,j)

0 a
1 b
2 c
__name__ 변수
>>> __name__
'__main__'
>>> if __name__ != '__main__':
	#해당 모듈에서만 실행하도록 하는게 가능
직접실행시에는 '__main__'으로 출력되지만, 모듈안에서 호출하면 해당 파일명으로 출력됨
type() 함수
>>> import time
>>> time.ctime()
'Wed Sep 19 14:19:08 2018'
>>> type(_)
<class 'str'>
>>> time.time()
1537334385.3130417
>>> type(_)
<class 'float'>
type(_)을 쓰면 최근 반환값을 자동으로 바인딩해서 보여줌
모듈 위치 확인
>>> import time
>>> time
<module 'time' (built-in)>
>>> import random
>>> random
<module 'random' from 'C:\\ProgramData\\Anaconda3\\lib\\random.py'>
time은 python이 아닌 c로 자여진 함수여서 직접 볼수 없기에 위처럼 표시됨
모듈 구성요소 확인
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'dic', 'i', 'j', 'os', 'random', 'stock', 'sys', 'tmp_d', 'x']
>>> #그냥 사용하면 현재 로드된 모듈이나 선언된 변수 모두를 보여줌
>>> import time
>>> dir(time)
['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'perf_counter', 'process_time', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname']
시간
>>> from datetime import date, time, datetime
>>> datetime.now()
datetime.datetime(2018, 9, 19, 14, 36, 58, 551407)
>>> dir(datetime)
['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fold', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year']
>>> datetime.now().strftime('%Y-%m-%d')
'2018-09-19'
>>> 
기호 의미 출력 예(2001-02-03 04:05:06 기준)
%Y 년 (네 자리) 2001
%y 년 (두 자리) 01
%m 월 (두 자리) 02
%d 일 (두 자리) 03
%A 요일 Saturday
%H 시 (24시간) 04
%I 시 (12시간) 04
%p 오전, 오후 AM
%M 분 (두 자리) 05
%S 초 (두 자리) 06
%f 마이크로초 000000
%% % 기호 %
현재경로, import 별칭
>>> import os as win_os
>>> win_os.getcwd()
'C:\\ProgramData\\Anaconda3\\Lib\\idlelib'
형변환
>>> int('5')
5
>>> str(12)
'12'
class와 self
>>> class A:
	 def fun1():
		 print('fun1')
	 def fun2(self):
		 print('fun2')
>>>
>>> class_A = A()
>>> #오류 - 파이썬 메서드의 첫번째 인자로 항상 인스턴스가 전달 되기 때문
>>> class_A.fun1()
Traceback (most recent call last):
  File "<pyshell#324>", line 1, in <module>
    class_A.fun1()
TypeError: fun1() takes 0 positional arguments but 1 was given
>>> class_A.fun2()
fun2
>>>
>>> A.fun1()
fun1
>>> #오류 - class A 자체가 네임스페이스로 되어 있기 때문에
>>> A.fun2()
Traceback (most recent call last):
  File "<pyshell#328>", line 1, in <module>
    A.fun2()
TypeError: fun2() missing 1 required positional argument: 'self'
>>> A.fun2(class_A)
fun2
>>>
클래스 네임스페이스
>>> class A:
	a = 'aaa'

>>> a = A()
>>> b = A()
>>>
>>> a.a = 'bbb'
>>>
>>> a.a
'bbb'
>>> b.a
'aaa'
>>> A.a
'aaa'
>>>
>>> dir(A)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a']
>>>
>>> A.__dict__
mappingproxy({'__module__': '__main__', 'a': 'aaa', '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None})
>>>
>>> a.__dict__
{'a': 'bbb'}
>>> b.__dict__
{}
네임스페이스 변수
>>> class B:
	cnt = 0
	def __init__(self):
		self.cnt+=1

>>> a = B()
>>> b = B()
>>> c = B()
>>> b.cnt
1
>>> a.cnt
1
>>> class B:
	cnt = 0
	def __init__(self):
		B.cnt+=1

>>>
>>> a = B()
>>> b = B()
>>> c = B()
>>> a.cnt
3
COM 예제
>>> # MS Word 실행(Word가 설치되어 있으면 구동)
>>> import win32com.client
>>> word = win32com.client.Dispatch("Word.Application")
>>> word.Visible = True
>>>
>>> # Internet Explorer 실행
>>> explorer = win32com.client.Dispatch('InternetExplorer.Application')
>>> explorer.Visible = True
COM으로 Excel 다루기
>>> #엑셀을 켠후에 Sheet1에 글을 쓰고 저장
>>> import win32com.client
>>> excel = win32com.client.Dispatch("Excel.Application")
>>> excel.Visible = True
>>> wb = excel.Workbooks.Add()
>>> ws = wb.Worksheets("Sheet1")
>>> ws.Cells(1, 1).Value = "Excel Save test"
>>> wb.SaveAs('C:\\test.xlsx')
>>> excel.Quit()