본문 바로가기

교육/Python 0309-0313

08. Library

https://wikidocs.net/33

import os


명령어 내리기

os.system(시스템명령어)

os.popen(시스템명령어)


작업디렉토리 알아내기

os.getcwd()


작업디렉토리 바꾸기

os.chdir(새경로)


경로만들기

os.path.join(경로1, 경로2...)


디렉토리 생성

os.mkdir(경로 [, mode=0777])


파일 또는 디렉토리 삭제

os.remove(파일경로)

os.rmdir(경로)


파일 또는 디렉토리 확인

os.path.exists(디렉토리경로)

os.path.isfile(파일경로)


import sys


명령행 인자 (python test.py arg1 arg2 arg3...)

sys.argv 로 접근가능. list임.


sys.copyright / sys.version / sys.stdin / sys.stdout / sys.stderr



import time


1970.01.01 이후로 누적된 초 반환

time.time 


프로세스를 주어진 초 만큼 멈춤

time.sleep(초)


입력된 초를 UTC 기준의 struct_time 객체로 반환. secs가 입력되지 않으면 현재시간을 사용

time.gettime([secs])


입력된 초를 지방표준시 기준의 struct_time 객체로 반환. secs가 입력되지 않으면 현재시간을 사용

time.localtime([secs])


struct_time 을 인자로 받아서 "Thu Mar 12 09:33:18 2015" 와 같이 string으로 반환

time.asctime([t])


struct_time 을 인자로 받아서 누적된 초를 반환

time.mktime(t)


struct_time 객체를 사용자가 정의한 형식의 문자열로 반환

time.strftime(format [,t])


사용자가 정의한 형식의 문자열을 struct_time 객체로 반환

time.strptime(string [,format])


struct_time 객체
time.struct_time(
tm_year=2015,
tm_mon=3,
tm_mday=12,
tm_hour=9,
tm_min=30,
tm_sec=40,
tm_wday=3,
tm_yday=71,
tm_isdst=0)
형식지정자내용
%y %Y연도를 출력 축약유무
%b %B월 이름을 출력 축약유무
%m월을 숫자로
%d일을 숫자로
%H24시 기준 시간
%I12시 기준 시간
%M분 표시
%S초 표시
%pAM/PM 표시
%a %A요일 출력 축약유무
%w요일을 숫자로
%j01.01 부터 누적된 날짜 (001 ~ 336) 표시





import datetime

일반적으로 사용하는 년,월,일로 표시되는 날짜
datetime.date(year, month, day)

타임스탬프 값을 인자로 date 객체반환
datetime.date.fromtimestamp(timestamp)

1년 1월 1일 이후로 누적된 날짜로부터 date 객체 반환
datetime.date.fromordinal(ordinal)

현재 시스템의 오늘 날짜 date 객체 반환
datetime.date.today()



import random


random.seed(a=None, version=2)

random.getstate()

random.setstate(state)

random.getrandbits(k)


정수

random.randrange(stop)

random.randrange(start, stop, [step])

random.randint(a,b)


실수

random.random()

random.uniform(a,b)

random.gauss(mu, sigma)




import logging


logging.basicConfig(filename="./log/my.log",

    filemode="a", level=logging.DEBUG, 

    format='[%(asctime)s][%(levelname)s] %(message)s')


format은 아래 표 참고

Attribute nameFormatDescription
argsYou shouldn’t need to format this yourself.The tuple of arguments merged into msg to produce message.
asctime%(asctime)sHuman-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time).
created%(created)fTime when the LogRecord was created (as returned by time.time()).
exc_infoYou shouldn’t need to format this yourself.Exception tuple (à la sys.exc_info) or, if no exception has occurred, None.
filename%(filename)sFilename portion of pathname.
funcName%(funcName)sName of function containing the logging call.
levelname%(levelname)sText logging level for the message ('DEBUG''INFO''WARNING''ERROR''CRITICAL').
levelno%(levelno)sNumeric logging level for the message (DEBUGINFOWARNINGERRORCRITICAL).
lineno%(lineno)dSource line number where the logging call was issued (if available).
module%(module)sModule (name portion of filename).
msecs%(msecs)dMillisecond portion of the time when the LogRecord was created.
message%(message)sThe logged message, computed as msg % args. This is set when Formatter.format() is invoked.
msgYou shouldn’t need to format this yourself.The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object (seeUsing arbitrary objects as messages).
name%(name)sName of the logger used to log the call.
pathname%(pathname)sFull pathname of the source file where the logging call was issued (if available).
process%(process)dProcess ID (if available).
processName%(processName)sProcess name (if available).
relativeCreated%(relativeCreated)dTime in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
thread%(thread)dThread ID (if available).
threadName%(threadName)sThread name (if available).


logging.info

logging.warn

logging.error

logging.critical



import pdb

breakpoint 지정

pdb.set_trace()


import pdb 안쓰고 디버그 모드로 수행하는 법

python -m pdb 


n다음라인수행
s함수안 수행
c다음 breakpoint 까지 이동
p 변수변수값 출력
l or ll현재디버그 위치 및 코드 보여줌
q

종료

b 숫자

숫자 라인에 breakpoint 설정 

bt

stack trace 출력 




3rd party library

install 하는 방법: python setup.py install


BeautifulSoup (xml / html parser) - http://www.crummy.com/software/BeautifulSoup/


XlsxWriter - https://xlsxwriter.readthedocs.org/ https://github.com/jmcnamara/XlsxWriter





'교육 > Python 0309-0313' 카테고리의 다른 글

10. Unit Test  (0) 2015.03.13
09. 문자열  (0) 2015.03.12
07. File IO  (0) 2015.03.11
06. 예외처리  (0) 2015.03.11
05. 상속  (0) 2015.03.11