[파이썬] 모듈의 기초 사용법과 내장 모듈들(sys, math, datetime, time, urllib) 살펴보기
표준 모듈
파이썬은 모듈이라는 기능을 통해 코드를 분리하고 공유함
모듈은 여러 변수와 함수를 가지고 있는 집합체로 표준모듈과 외부모듈로 나뉨
- 표준모듈 - 파이썬 기본 내장 모듈
- 외장모듈 - 다른사람이 만든 모듈
모듈을 만들땐 기본적으로 import 구문을 작성하며 이는 코드 가장 위에 작성한다
import math
math 모듈
math 모듈 사용법
import math
math 모듈을 위와 같이 import 하면 math 모듈을 사용할 수 있다
math 모듈 안엔 수학과 관련된 함수들이 저장되어 있다
math.sin(1)
0.8414709848078965
math.cos(1)
0.5403023058681398
math.tan(1)
1.5574077246549023
모듈 문서
표준모듈의 정보가 궁금할땐 파이썬 공식 문서를 보는게 정확하다
from 구문
모듈에는 많은 변수와 함수가 있기 때문에 이를 from 구문을 사용해 가져오고 싶은 변수나 함수를 입력해 이것만 가져올 수 있다
from 구문을 사용해 가져온 함수나 변수들은 앞에 모듈명을 붙이지 않아도 사용이 가능하다
from math import sin, cos, tan,floor, ceil
sin(1)
0.8414709848078965
cos(1)
0.5403023058681398
tan(1)
1.5574077246549023
모두 가져오기
만약 변수나 함수 앞에 모듈명은 붙이기 싫지만 모듈에 있는 모든 함수와 변수를 import 하고 싶다면 “*”을 사용하여 모두 가져올 수 있다
from math import *
단 모든 걸 다 가져오면 식별자 이름 충돌이 발생할 수 있으니 왠만해선 from 구문 사용시 필요한 것만 가져와서 사용하도록 하자
as 구문
모듈을 가져올 때 모듈의 이름이 너무 길거나 코드에 있는 식별자와 이름이 충돌할 경우 as 구문을 통해 별명을 지어줄 수 있다
import math as m
#import 모듈 as 별명
이를 사용하면 모듈의 이름을 바꿔서 사용할 수 있다
random 모듈
random 모듈은 랜덤한 값을 생성할 때 사용되는 모듈이다
import random
from random import random, uniform, randrange, choice, shuffle, sample
print('random module')
#random() -> 0.0 <= x < 1.0 사이의 float을 반환함
print('random()', random())
#uniform(min, max) -> 지정한 범위 사이의 float을 리턴함
print('uniform(min, max)', uniform(10,20))
#randrange() -> 지정한 범위 내 int를 리턴함
#randrange(max) -> 0부터 max 사이의 int 리턴
#randrange(min, max) -> min부터 max 사이의 int 리턴턴
print('randrange(10)', randrange(10))
#choice(list) -> 리스트 내부에 있는 요소를 랜덤으로 선택
print('choice([1,2,3,4,5])', choice([1,2,3,4,5]))
#shuffle(list) -> 리스트의 요소를 랜덤하게 섞는다
print('shuffle([1,2,3,4,5])', shuffle([1,2,3,4,5]))
#sample(list, k=숫자) -> 리스트 요소 중에 k개를 뽑는다
print('sample([1,2,3,4,5],k=2)', sample([1,2,3,4,5],k=2))
#result
random module
random() 0.6794378762692332
uniform(min, max) 16.434095824634667
randrange(10) 4
choice([1,2,3,4,5]) 3
shuffle([1,2,3,4,5]) None
sample([1,2,3,4,5],k=2) [4, 5]
sys 모듈
시스템과 관련된 정보를 가지고 있는 모듈이다
명령 매개변수를 받을때 자주 사용하는 모듈이다
import sys
print(sys.argv)
print('===')
#컴퓨터 환경과 관련된 정보 출력
print("sys.getwindowsversion()", sys.getwindowsversion())
print('---')
print("sys.copyright", sys.copyright())
print('---')
print("sys.version",sys.version())
#프로그램을 강제종료한다
sys.exit()
#result
sys.getwindowsversion() sys.getwindowsversion(major=10, minor=0, build=26100, platform=2, service_pack='')
---
sys.copyright Copyright (c) 2001-2024 Python Software Foundation.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
---
sys.version 3.13.1 (tags/v3.13.1:0671451, Dec 3 2024, 19:06:28) [MSC v.1942 64 bit (AMD64)]
상단의 sys.argv는 명령 프롬프트 창에서 입력할 수 있는 명령 매개변수이다.
python module_sys.py 10,20,30
#10,20,30이 모듈 매개변수
#result
['module_sys.py', '10,20,30']
os 모듈
운영체제와 관련된 기능을 가진 모듈
새로운 폴더를 만들거나 폴더 내부 파일 목록을 보는 일을 모두 처리함
from os import name, getcwd, listdir, mkdir, rmdir, rename, remove, system
print('os', name)
print('current folder', getcwd())
print('inside elem in current folder', listdir)
#폴더 만들고 제거하기
mkdir("Hello")
rmdir("Hello")
#파일 만들고 이름 바꾸기
with open("original.txt","w") as file:
file.write("Hello")
rename("original.txt","new.txt")
#파일 제거
remove("new.txt")
#시스템 명령어 실행
system("dir")
#result
2025-02-12 오전 10:12 <DIR> .
2025-02-12 오전 09:47 <DIR> ..
2025-02-12 오전 10:12 465 module_os.py
2025-02-12 오전 10:04 302 module_sys.py
2025-02-12 오전 09:55 889 random_module.py
3개 파일 1,656 바이트
2개 디렉터리 86,883,889,152 바이트 남음
datetime 모듈
datetime 모듈은 날짜, 시간과 관련된 모듈로, 날짜 형식을 만들 때 자주 사용하는 코드들로 구성되어 있다
import datetime
#현재 시간 구하기
print('#현재 시각 출력하기')
now = datetime.datetime.now()
print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)
print()
print('#시간을 포맷에 맞춰 출력하기')
output_a = now.strftime("%Y.%m.%d %H:%M:%S")
output_b = "{}년 {}월 {}일 {}시 {}분 {}초".format(now.year, now.month, now.day, now.hour, now.minute, now.second)
output_c = now.strftime("%Y{} %m{} %d{} %H{} %M{} %S{}").format(*"년월월일시분초")
print(output_a)
print(output_b)
print(output_c)
#result
2025
2
12
10
25
32
#시간을 포맷에 맞춰 출력하기
2025.02.12 10:25:32
2025년 2월 12일 10시 25분 32초
2025년 02월 12월 10일 25시 32분
strftime 매서드
strftime
용도 | 주어진 포맷에 따라 객체를 문자열로 변환합니다 |
메서드의 형 | 인스턴스 메서드 |
메서드가 제공되는 곳 | date; datetime; time |
서명 | strftime(format) |
지시자 의미 예 노트
%a | 요일을 로케일의 축약된 이름으로. | Sun, Mon, …, Sat (en_US);So, Mo, …, Sa (de_DE) | (1) |
%A | 요일을 로케일의 전체 이름으로. | Sunday, Monday, …, Saturday (en_US);Sonntag, Montag, …, Samstag (de_DE) | (1) |
%w | 요일을 10진수로, 0은 일요일이고 6은 토요일입니다. | 0, 1, …, 6 | |
%d | 월중 일(day of the month)을 0으로 채워진 10진수로. | 01, 02, …, 31 | (9) |
%b | 월을 로케일의 축약된 이름으로. | Jan, Feb, …, Dec (en_US);Jan, Feb, …, Dez (de_DE) | (1) |
%B | 월을 로케일의 전체 이름으로. | January, February, …, December (en_US);Januar, Februar, …, Dezember (de_DE) | (1) |
%m | 월을 0으로 채워진 10진수로. | 01, 02, …, 12 | (9) |
%y | 세기가 없는 해(year)를 0으로 채워진 10진수로. | 00, 01, …, 99 | (9) |
%Y | 세기가 있는 해(year)를 10진수로. | 0001, 0002, …, 2013, 2014, …, 9998, 9999 | (2) |
%H | 시(24시간제)를 0으로 채워진 십진수로. | 00, 01, …, 23 | (9) |
%I | 시(12시간제)를 0으로 채워진 십진수로. | 01, 02, …, 12 | (9) |
%p | 로케일의 오전이나 오후에 해당하는 것. | AM, PM (en_US);am, pm (de_DE) | (1), (3) |
%M | 분을 0으로 채워진 십진수로. | 00, 01, …, 59 | (9) |
%S | 초를 0으로 채워진 10진수로. | 00, 01, …, 59 | (4), (9) |
%f | Microsecond as a decimal number, zero-padded to 6 digits. | 000000, 000001, …, 999999 | (5) |
%z | ±HHMM[SS[.ffffff]] 형태의 UTC 오프셋 (객체가 나이브하면 빈 문자열). | (비어 있음), +0000, -0400, +1030, +063415, -030712.345216 | (6) |
%Z | 시간대 이름 (객체가 나이브하면 빈 문자열). | (비어 있음), UTC, GMT | (6) |
%j | 연중 일(day of the year)을 0으로 채워진 십진수로. | 001, 002, …, 366 | (9) |
%U | Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. | 00, 01, …, 53 | (7), (9) |
%W | Week number of the year (Monday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the first Monday are considered to be in week 0. | 00, 01, …, 53 | (7), (9) |
%c | 로케일의 적절한 날짜와 시간 표현. | Tue Aug 16 21:30:00 1988 (en_US);Di 16 Aug 21:30:00 1988 (de_DE) | (1) |
%x | 로케일의 적절한 날짜 표현. | 08/16/88 (None);08/16/1988 (en_US);16.08.1988 (de_DE) | (1) |
%X | 로케일의 적절한 시간 표현. | 21:30:00 (en_US);21:30:00 (de_DE) | (1) |
%% | 리터럴 '%' 문자. | % |
C89 표준에서 요구하지 않는 몇 가지 추가 지시자가 편의상 포함되어 있습니다. 이 파라미터들은 모두 ISO 8601 날짜 값에 해당합니다.
지시자 의미 예 노트
%G | ISO 주(%V)의 더 큰 부분을 포함하는 연도를 나타내는 세기가 있는 ISO 8601 연도. | 0001, 0002, …, 2013, 2014, …, 9998, 9999 | (8) |
%u | ISO 8601 요일을 10진수로, 1은 월요일입니다. | 1, 2, …, 7 | |
%V | ISO 8601 주를 월요일을 주의 시작으로 하는 십진수로. 주 01은 1월 4일을 포함하는 주입니다. | 01, 02, …, 53 | (8), (9) |
%:z | UTC offset in the form ±HH:MM[:SS[.ffffff]] (empty string if the object is naive). | (empty), +00:00, -04:00, +10:30, +06:34:15, -03:07:12.345216 | (6) |
*파이썬 공식 문서 참조
time 모듈
시간과 관련된 기능을 다룰 땐 time 모듈을 사용함
time 모듈은 유닉스 타임 (1970년 1월 1일 00시 00분 00초)를 기준으로 계산한 단위)를 구할 때나 특정 시간동안 코드를 정지시킬 때 사용함
import time
print('5초 정지')
time.sleep(5)
print('exit prog')
매우 자주 사용하는 기능임!
urllib 모듈
URL을 다루는 모듈
from urllib import request
#urlopen() 함수로 구글의 메인 페이지 읽기
target = request.urlopen("<https://google.com>")
output = target.read()
#출력
print(output)
#result
b'(function(){var _g={kEI:\\'yfurZ8-QD7Sfvr0PotzawAg\\',kEXPI:\\'0,18167,3682146,636,435,302126,236535,2872,2891,43028,30022,16105,344796,212051,35268,11814,11342,19569,5230292,10463,766,5988808,2846292,4,28,3,24,10,7437695,184,20539755,25228681,65456,57648,15164,8181,5936,8450,3490,31554,21667,6757,23878,9139,745,2,2,3851,328,6225,2949,7469,13947,3625,6320,19899,9956,1341,13707,49,8164,7422,12132,2388,6782,33,9041,17667,10672,4553,2,6343,14928,3853,41,13639,1,4914,1827,2895,1211,306,18517,7230,2149,4614,5773,4311,2326,1310,738,4797,1439,1874,624,583,6728,2882,820,2850,7411,5443,2109,3,1142,8,40,2,416,1639,890,15,1651,465,1326,714,1789,70,3,2,1179,56,1026,1,142,686,221,1,701,1933,1678,1546,2,831,903,569,938,1,6,279,1142,1205,1032,741,142,3303,227,170,1359,639,354,1030,14,139,3,971,1548,705,1078,285,7,828,6,1553,895,163,851,342,15,360,225,812,3,2,1,2,2,2,3,99,886,88,369,231,69,98,118,11,136,614,291,310,58,979,566,325,11,2010,505,504,51,284,2,716,572,4,132,327,266,31,340,599,947,523,111,292,591,1795,344,506,568,118,191,75,159,231,43,16,4,98,96,496,9,7,60,401,86,117,26,2249,64,784,160,532,61,25,168,529,248,184,367,264,3,953,739,662,192,21359028,18,2013,45,1166,1316,8,3873,12,4657,2053,8017402\\',kBL:\\'6jTk\\',kOPI:89978449};(function(){var a;((a=window.google)==null?0:a.stvsc)?google.kEI=_g.kEI:window.google=_g;}).call(this);})();(function(){google.sn=\\'webhp\\';google.kHL=\\'ko\\';})();(function(){\\nvar g=this||self;function k(){return window.google&&window.google.kOPI||null};var l,m=[];function n(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||l}function p(a){for(var b=null;a&&(!a.getAttribute||!(b=a.getAttribute("leid")));)a=a.parentNode;return b}function q(a){/^http:/i.test(a)&&window.location.protocol==="https:"&&(google.ml&&google.ml(Error("a"),!1,{src:a,glmm:1}),a="");return a}\\nfunction r(a,b,d,c,h){var e="";b.search("&ei=")===-1&&(e="&ei="+n(c),b.search("&lei=")===-1&&(c=p(c))&&(e+="&lei="+c));var f=b.search("&cshid=")===-1&&a!=="slh";c="&zx="+Date.now().toString();g._cshid&&f&&(c+="&cshid="+g._cshid);(d=d())&&(c+="&opi="+d);return"/"+(h||"gen_204")+"?atyp=i&ct="+String(a)+"&cad="+(b+e+c)};l=google.kEI;google.getEI=n;google.getLEI=p;google.ml=function(){return null};google.log=function(a,b,d,c,h,e){e=e===void 0?k:e;d||(d=r(a,b,e,c,h));if(d=q(d)){a=new Image;var f=m.length;m[f]=a;a.onerror=a.onload=a.onabort=function(){delete m[f]};a.src=d}};google.logUrl=function(a,b){b=b===void 0?k:b;return r("",a,b)};}).call(this);(function(){google.y={};google.sy=[];var d;(d=google).x||(d.x=function(a,b){if(a)var c=a.id;else{do c=Math.random();while(google.y[c])}google.y[c]=[a,b];return!1});var e;(e=google).sx||(e.sx=function(a){google.sy.push(a)});google.lm=[];var f;(f=google).plm||(f.plm=function(a){google.lm.push.apply(google.lm,a)});google.lq=[];var g;(g=google).load||(g.load=function(a,b,c){google.lq.push([[a],b,c])});var h;(h=google).loadAll||(h.loadAll=function(a,b){google.lq.push([a,b])});google.bx=!1;var k;(k=google).lx||(k.lx=function(){});var l=[],m;(m=google).fce||(m.fce=function(a,b,c,n){l.push([a,b,c,n])});google.qce=l;}).call(this);google.f={};(function(){\\ndocument.documentElement.addEventListener("submit",function(b){var a;if(a=b.target){var c=a.getAttribute("data-submitfalse");a=c==="1"||c==="q"&&!a.elements.q.value?!0:!1}else a=!1;a&&(b.preventDefault(),b.stopPropagation())},!0);document.documentElement.addEventListener("click",function(b){var a;a:{for(a=b.target;a&&a!==document.documentElement;a=a.parentElement)if(a.tagName==="A"){a=a.getAttribute("data-nohref")==="1";break a}a=!1}a&&b.preventDefault()},!0);}).call(this);(function(){window.google.erd={jsr:1,bv:2166,de:true,dpf:\\'kmhfW8vbGiXnSkgkHRLF1E1g2FxQO_2FIaLr8tQwnCI\\'};\\nvar g=this||self;var k,l=(k=g.mei)!=null?k:1,m,p=(m=g.diel)!=null?m:0,q,r=(q=g.sdo)!=null?q:!0,t=0,u,w=google.erd,x=w.jsr;google.ml=function(a,b,d,n,e){e=e===void 0?2:e;b&&(u=a&&a.message);d===void 0&&(d={});d.cad="ple_"+google.ple+".aple_"+google.aple;if(google.dl)return google.dl(a,e,d,!0),null;b=d;if(x<0){window.console&&console.error(a,b);if(x===-2)throw a;b=!1}else b=!a||!a.message||a.message==="Error loading script"||t>=l&&!n?!1:!0;if(!b)return null;t++;d=d||{};b=encodeURIComponent;var c="/gen_204?atyp=i&ei="+b(google.kEI);google.kEXPI&&(c+="&jexpid="+b(google.kEXPI));c+="&srcpg="+b(google.sn)+"&jsr="+b(w.jsr)+\\n"&bver="+b(w.bv);w.dpf&&(c+="&dpf="+b(w.dpf));var f=a.lineNumber;f!==void 0&&(c+="&line="+f);var h=a.fileName;h&&(h.indexOf("-extension:/")>0&&(e=3),c+="&script="+b(h),f&&h===window.location.href&&(f=document.documentElement.outerHTML.split("\\\\n")[f],c+="&cad="+b(f?f.substring(0,300):"No script found.")));google.ple&&google.ple===1&&(e=2);c+="&jsel="+e;for(var v in d)c+="&",c+=b(v),c+="=",c+=b(d[v]);c=c+"&emsg="+b(a.name+": "+a.message);c=c+"&jsst="+b(a.stack||"N/A");c.length>=12288&&(c=c.substr(0,12288));a=c;n||google.log(0,"",a);return a};window.onerror=function(a,b,d,n,e){u!==a&&(a=e instanceof Error?e:Error(a),d===void 0||"lineNumber"in a||(a.lineNumber=d),b===void 0||"fileName"in a||(a.fileName=b),google.ml(a,!1,void 0,!1,a.name==="SyntaxError"||a.message.substring(0,11)==="SyntaxError"||a.message.indexOf("Script error")!==-1?3:p));u=null;r&&t>=l&&(window.onerror=null)};})();(function(){var src=\\'/images/nav_logo229.png\\';var iesg=false;document.body.onload = function(){window.n && window.n();if (document.images){new Image().src=src;}\\nif (!iesg){document.f&&document.f.q.focus();document.gbqf&&document.gbqf.q.focus();}\\n}\\n})();
실행 결과를 보면 앞에 ‘b’가 붙어있다
이는 바이너리 데이터를 의미한다