Introducing Python(처음 시작하는 파이썬)
Chapter 10. 시스템
※ Module \(\texttt{os}\)는 다양한 System Call을 포함하고 있다.
10.1 Files (파일)
* Python File Management Functions
- open() Function
- exists() Function
- isfile() Function
- isdir() Function
- isabs() Function
- copy() Function
- move() Function
- rename() Function
- link() Function
- symlink() Function
- islink() Function
- chmod() Function
- chown() Function
- abspath() Function
- realpath() Function
- remove() Function
open() Function (open() 함수)
- Python Script상에서 File을 연다.
Example. open() Function Usage
>>> fout = open('oops.txt', 'wt')
>>> print('Oops, I created a file.', file=fout)
>>> fout.close()
exists() Function (exists() 함수)
- File 혹은 Directory가 실제로 존재하는지에 대한 여부를 리턴한다.
Example. exists() Function Usage
>>> import os
>>> os.path.exists('oops.txt')
True
>>> os.path.exists('./oops.txt')
True
>>> os.path.exists('waffles')
False
>>> os.path.exists('.')
True
>>> os.path.exists('..')
True
isfile() Function (isfile() 함수)
- Argument로 입력된 이름이 File인지에 대한 여부를 리턴한다.
Example. isfile() Function Usage
>>> name = 'oops.txt'
>>> os.path.isfile(name)
True
isdir() Function (isdir() 함수)
- Argument로 입력된 이름이 Directory인지에 대한 여부를 리턴한다.
Example. isdir() Function Usage
>>> name = 'oops.txt'
>>> os.path.isdir(name)
False
>>> os.path.isdir('.') # . means Current Directory
True
>>> os.path.isdir('..') # . means Parent Directory
True
isabs() Function (isabs() 함수)
- Argument로 입력된 이름이 Absolute Path인지에 대한 여부를 리턴한다.
- Argument가 실제로 시스템에 존재하는 파일일 필요는 없다.
Example. isabs() Function
>>> name = 'oops.txt'
>>> os.path.isabs(name)
False
>>> os.path.isabs('/big/fake/name')
True
>>> os.path.isabs('big/fake/name/without/a/leading/slash')
False
copy() Function (copy() 함수)
- Module shutil에 포함되어 있다.
Example. copy() Function Usage
>>> import shutil
>>> shutil.copy('oops.txt', 'ohno.txt')
move() Function (move() 함수)
- Module shutil에 포함되어 있다.
rename() Function (rename() 함수)
- 파일의 이름을 변경한다.
Example. rename() Function Usage
>>> import os
>>> os.rename('ohno.txt', 'ohwell.txt')
link() Function (link() 함수)
- File에 대한 Hard Link를 생성한다.
Example. link() Function Usage
>>> os.link('oops.txt', 'yikes.txt')
>>> os.path.isfile('yikes.txt')
True
* Hard Link vs Symbolic Link in UNIX (URL)
symlink() Function (symlink() 함수)
- File에 대한 Symbolic Link를 생성한다.
Example. symlink() Function Usage
>>> os.path.islink('yikes.txt')
False
>>> os.symlink('oops.txt', 'jeepers.txt')
>>> os.path.islink('jeepers.txt')
True
* Hard Link vs Symbolic Link in UNIX (URL)
islink() Function (islink() 함수)
- 전달받은 File이름이 Symbolic Link인지에 대한 여부를 리턴한다.
Example. islink() Function Usage
>>> os.path.islink('yikes.txt')
False
>>> os.symlink('oops.txt', 'jeepers.txt')
>>> os.path.islink('jeepers.txt')
True
chmod() Function (chmod() 함수)
- File의 Permission을 변경한다.
(Permission에는 Read, Write, Execute 권한이 있다.)
- 미리 정의된 8진수 값으로 Permission의 종류를 선택한다.
(혹은 stat 모듈에 정의된 상수를 이용할 수도 있다.)
Example. chmod() Function Usage
>>> os.chmod('oops.txt', 0o400)
# oops.txt 파일은 파일을 생성한 사용자만ㄴ 읽을 수 있다.
>>> import stat
>>> os.chmod('oops.txt', stat.S_IRUSR)
# Module stat에 정의된 상수를 사용하여 Permission을 변경할 수도 있다.
# stat.S_IRUSR은 0o400과 같다.
chown() Function (chown() 함수)
- uid(사용자 아이디)와 gid(그룹 아이디)를 지정하여 File의 소유자와 그룹에 대한 Ownership을 변경할 수 있다.
- 이 함수는 UNIX, Linux, MAC에서 사용된다.
Example. chown() Function Usage
>>> uid = 5
>>> gid = 22
>>> os.chown('oops', uid, gid)
abspath() Function (abspath() 함수)
- 상대 경로를 절대 경로로 변환하여 리턴한다.
Example. abspath() Function Usage
>>> os.path.abspath('oops.txt')
'/usr/gaberlunzie/oops.txt'
realpath() Function (realpath() 함수)
- Symbolic Link의 Absolute Path를 리턴한다.
Example. realpath() Function Usage
>>> os.symlink('oops.txt', 'jeepers.txt')
>>> os.path.realpath('jeepers.txt')
'/usr/gaberlunzie/oops.txt'
remove() Function (remove() 함수)
- 파일을 삭제한다.
Example. remove() Function Usage
>>> os.remove('oops.txt')
>>> os.path.exists('oops.txt')
False
10.2 Directories (디렉터리)
* Python Directory Management Functions
- mkdir() Function
- rmdir() Function
- listdir() Function
- chdir() Function
- glob() Function
mkdir() Function (mkdir() 함수)
- 디렉터리를 생성한다.
Example. mkdir() Function Usage
>>> os.mkdir('poems')
>>> os.path.exists('poems')
True
rmdir() Function (rmdir() 함수)
- 디렉터리를 삭제한다.
Example. rmdir() Function Usage
>>> os.rmdir('poems')
>>> os.path.exists('poems')
False
listdir() Function (listdir() 함수)
- 디렉터리의 콘텐츠를 나열한다.
Example. listdir() Function Usage
>>> os.mkdir('poems')
>>> os.listdir('poems')
[]
>>> os.mkdir('poems/mcintyre')
>>> os.listdir('poems')
['mcintyre']
chdir() Function (chdir() 함수)
- 현재 디렉터리를 변경한다.
Example. chdir() Function Usage
>>> import os
>>> os.chdir('poems')
>>> os.listdir('.')
['mcintyre']
glob() Function (glob() 함수)
- UNIX Shell 규칙을 기반으로, 검색어에 일치하는 파일이나 디렉터리를 검색한다.
* UNIX Shell Rules
UNIX Shell Rules | Descroption |
* | 모든 것에 일치 |
? | 한 문자에 일치 |
[abc] | a 혹은 b 혹은 c 문자에 일치 |
[!abc] | a, b, c를 제외한 문자들에 일치 |
Example. glob() Function Usage
>>> import glob
>>> glob.glob('m*')
['mcintyre']
>>> glob.glob('??')
[]
>>> glob.glob('m??????e')
['mcintyre']
>>> glob.glob('[klm]*e')
['mcintyre']
10.3 Programs and Processes (프로그램과 프로세스)
getpid() Function (getpid() 함수)
- 실행중인 Python Interpreter에 대한 Process ID를 리턴한다.
getcwd() Function (getcwd() 함수)
- Currnet Working Directory의 Path를 리턴한다.
getuid() Function (getuid() 함수)
- User ID를 리턴한다.
getgid() Function (getgid() 함수)
- Group ID를 리턴한다.
Module: subprocess
- Python Standard Library이다.
- 현재 프로그램에서 다른 프로그램을 시작하거나 멈출 수 있다.
getoutput() Function
- Shell Command를 Argument로 받는다.
Example. getoutput() Function Usage
>>> import subprocess
>>> ret = subprocess.getoutput('date')
# 현재 프로그램에서 date라는 프로그램의 결과값을 얻어온다.
>>> ret
'Sun Mar 30 22:54:37 CDT 2014'
>>> ret = subprocess.getoutput('date -u')
>>> ret
'Mon Mar 31 03:55:01 UTC 2014'
>>> ret = subprocess.getoutput('date -u | wc')
>>> ret
' 1 6 29'
check_output() Function
- 표준 출력으로 String이 아닌, Byte Type을 리턴한다.
- Shell을 사용하지 않는다.
Example. check_output() Function Usage
>>> ret = subprocess.check_output(['date', '-u'])
>>> ret
b'Mon Mar 31 04:01:50 UTC 2014\n'
getstatusoutput() Function
- 프로그램의 Status Code와 결과값을 Tuple로 리턴한다.
Example. getstatusoutput() Function Usage
>>> ret = subprocess.getstatusoutput('date')
>>> ret
(0, 'Sat Jan 18 21:36:23 CST 2014')
call() Function
- 프로그램의 Status Code를 리턴한다.
Example. call() Function Usage
>>> ret = subprocess.call('date')
Sat Jan 18 21:33:11 CST 2014
>>> ret
0
>>> ret = subprocess.call('date -u', shell=True)
Tue Jan 21 04:40:04 UTC 2014
>>> ret = subprocess.call(['date', '-u'])
Tue Jan 21 04:41:59 UTC 2014
Module: multiprocessing
- Python Function을 별도의 Process로 실행할 수 있게 한다.
- 한 프로그램에서 독립적인 여러 Process를 실행할 수 있게 한다.
- Interprocess Communication Mechanism, Queue Task, Starvation 해결방안 등을 제공하고 있다.
Process() Function
- 새 Process를 생성하고, Task를 할당한다.
Example. Process() Function Usage
import multiprocessing
import os
def do_this(what):
whoami(what)
def whoami(what):
print("Process %s says: %s" % (os.getpid(), what))
if __name__ == "__main__":
whoami("I'm the main program")
for n in range(4):
p = multiprocessing.Process(target=do_this,
args=("I'm function %s" % n,))
# 새 Process를 생성하여 do_this() 함수를 실행시킨다.
p.start()
# Execution Results
Process 6224 says: I'm the main program
Process 6225 says: I'm function 0
Process 6226 says: I'm function 1
Process 6227 says: I'm function 2
Process 6228 says: I'm function 3
terminate() Function
- Process를 종료한다.
Example. terminate() Function Usage
import multiprocessing
import time
import os
def whoami(name):
print("I'm %s, in process %s" % (name, os.getpid()))
def loopy(name):
whoami(name)
start = 1
stop = 1000000
for num in range(start, stop):
print("\tNumber %s of %s. Honk!" % (num, stop))
time.sleep(1)
if __name__ == "__main__":
whoami("main")
p = multiprocessing.Process(target=loopy, args=("loopy",))
p.start()
time.sleep(5)
p.terminate()
# Execution Results
I'm main, in process 97080
I'm loopy, in process 97081
Number 1 of 1000000. Honk!
Number 2 of 1000000. Honk!
Number 3 of 1000000. Honk!
Number 4 of 1000000. Honk!
Number 5 of 1000000. Honk!
10.4 Calendars and Clocks (달력과 시간)
Module: calendar
isleap() Function
- Argument로 입력된 연도 값이 Leap Year(윤년)인지에 대한 여부를 출력한다.
Example. isleap() Function Usage
>>> import calendar
>>> calendar.isleap(1900)
False
>>> calendar.isleap(1996)
True
>>> calendar.isleap(1999)
False
>>> calendar.isleap(2000)
True
>>> calendar.isleap(2002)
False
>>> calendar.isleap(2004)
True
Module: datetime
date Object
- 년, 월, 일
- 날짜의 범위는 date.min(year=1, month=1, day=1)부터 date.max(year=9999, month=12, day=31)까지이다.
(즉, 역사적, 천문학적 날짜는 계산할 수 없다.)
time Object
- 시, 분, 초, 마이크로초
- 마이크로초 측정의 정확성은 H/W와 OS에 따라 달라짐에 유의해야 한다.
datetime Object
- 날짜와 시간
timedelta Object
- 날짜, 시간 간격
Example. datetime Module Usage
>>> from datetime import date
>>> halloween = date(2014, 10, 31)
>>> halloween
datetime.date(2014, 10, 31)
>>> halloween.day
31
>>> halloween.month
10
>>> halloween.year
2014
>>> halloween.isoformat()
'2014-10-31'
>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2014, 2, 2)
>>> from datetime import timedelta
>>> one_day = timedelta(days=1)
>>> tomorrow = now + one_day
>>> tomorrow
datetime.date(2014, 2, 3)
>>> now + 17*one_day
datetime.date(2014, 2, 19)
>>> yesterday = now - one_day
>>> yesterday
datetime.date(2014, 2, 1)
>>> from datetime import time
>>> noon = time(12, 0, 0)
>>> noon
datetime.time(12, 0)
>>> noon.hour
12
>>> noon.minute
0
>>> noon.second
0
>>> noon.microsecond
0
>>> from datetime import datetime
>>> some_day = datetime(2014, 1, 2, 3, 4, 5, 6)
>>> some_day
datetime.datetime(2014, 1, 2, 3, 4, 5, 6)
>>> some_day.isoformat()
'2014-01-02T03:04:05.000006'
# 문자열 중간의 T는 날짜와 시간을 구분짓는 역할을 한다.
>>> from datetime import datetime
>>> now = datetime.now()
>>> now
datetime.datetime(2014, 2, 2, 23, 15, 34, 694988)
14
>>> now.month
2
>>> now.day
2
>>> now.hour
23
>>> now.minute
15
>>> now.second
34
>>> now.microsecond
694988
>>> from datetime import datetime, time, date
>>> noon = time(12)
>>> this_day = date.today()
>>> noon_today = datetime.combine(this_day, noon)
>>> noon_today
datetime.datetime(2014, 2, 2, 12, 0)
>>> noon_today.date()
datetime.date(2014, 2, 2)
>>> noon_today.time()
datetime.time(12, 0)
Module: time
- datime Module의 time Object와 구분되는, 별개의 Module이다.
* Epoch
- 1970년 1월 1일 자정 이후 경과된 시간값을 초 단위로 환산한 값이다.
- Epoch값은 시스템 간 날짜, 시간을 교환하는데 쓰인다.
time() Function
- 현재 시간에 대한 Epoch 값을 리턴한다.
ctime() Function
- Epoch값을 날짜와 시간을 표현하는 String으로 변환하여 리턴한다.
Example. time(), ctime() Function Usage
>>> import time
>>> now = time.time()
>>> now
1391488263.664645
>>> time.ctime(now)
'Mon Feb 3 22:31:03 2014'
struct_time Object
- 날짜와 시간 요소를 얻을 때 사용하는 Object이다.
localtime() Function
- 시스템의 표준시간대로 시간을 리턴한다.
gmtime() Function
- UTC 시간을 리턴한다.
※ Server Program에서는 표준시간대와 독립적이고, 절대적 시간인 UTC를 사용하는것이 적절하고,
Summer Time을 사용하지 않는 것이 바람직하다.
- Summer Time을 적용하게 되면, 연중 한 시간이 다른 시간에 두번 발생하게 된다.
(즉, 봄이 앞당겨지고, 가을이 늦게 오게 된다.)
mktime() Function
- struct_time Object를 Epoch로 변환하여 리턴한다.
Example. struct_time Obejct Usage
>>> time.localtime(now)
time.struct_time(tm_year=2014, tm_mon=2, tm_mday=3, tm_hour=22, tm_min=31,
tm_sec=3, tm_wday=0, tm_yday=34, tm_isdst=0)
>>> time.gmtime(now)
time.struct_time(tm_year=2014, tm_mon=2, tm_mday=4, tm_hour=4, tm_min=31,
tm_sec=3, tm_wday=1, tm_yday=35, tm_isdst=0)
strftime() Function
- datetime, date, time 객체에서 Method로 제공되고,
time 모듈에서 Function으로 제공된다.
- Format String을 이용하여 사용자가 원하는 형식으로 날짜와 시간을 출력할 수 있게 한다.
* Output Specifiers for strftime()
Format String | Date/Time Unit | Range |
%Y | 년 | 1900 ~ |
%m | 월 | 01 ~ 12 |
%B | 월 이름 | January ~ |
%b | 월 축약 이름 | Jan ~ |
%d | 월의 일자 | 01 ~ 31 |
%A | 요일 이름 | Sunday ~ |
%a | 요일 축약 이름 | Sun ~ |
%H | 24시간 | 00 ~ 23 |
%I | 12시간 | 01 ~ 12 |
%p | 오전/오후 | AM, PM |
%M | 분 | 00 ~ 59 |
%S | 초 | 00 ~ 59 |
Example. strftime() Function Usage
>>> import time
>>> fmt = "It's %A, %B %d, %Y, local time %I:%M:%S%p"
>>> t = time.localtime()
>>> t
time.struct_time(tm_year=2014, tm_mon=2, tm_mday=4, tm_hour=19,
tm_min=28, tm_sec=38, tm_wday=1, tm_yday=35, tm_isdst=0)
>>> time.strftime(fmt, t)
"It's Tuesday, February 04, 2014, local time 07:28:38PM"
>>> from datetime import date
>>> some_day = date(2014, 7, 4)
>>> fmt = "It's %B %d, %Y, local time %I:%M:%S%p"
>>> some_day.strftime(fmt)
"It's Friday, July 04, 2014, local time 12:00:00AM"
>>> from datetime import time
>>> some_time = time(10, 35)
>>> some_time.strftime(fmt)
"It's Monday, January 01, 1900, local time 10:35:00AM"
# time Object는 시간만 다루므로, 날짜값은 모두 무시된다.
strptime() Function
- String을 날짜나 시간으로 변환하여 리턴한다.
- Argument로 입력되는 String과 Format String이 정확히 일치해야 한다.
Example. strptime() Function Usage
>>> import time
>>> fmt = "%Y-%m-%d"
>>> time.strptime("2012 01 29", fmt)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/
python3.3/_strptime.py", line 494, in _strptime_time
tt = _strptime(data_string, format)[0]
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/
python3.3/_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data '2012 01 29' does not match format '%Y-%m-%d'
>>> time.strptime("2012-01-29", fmt)
time.struct_time(tm_year=2012, tm_mon=1, tm_mday=29, tm_hour=0, tm_min=0,
tm_sec=0, tm_wday=6, tm_yday=29, tm_isdst=-1)
>>> time.strptime("2012-13-29", fmt)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/
python3.3/_strptime.py", line 494, in _strptime_time
tt = _strptime(data_string, format)[0]
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/
python3.3/_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data '2012-13-29' does not match format '%Y-%m-%d'
locale Module
- 날짜와 시간 명칭을 각 나라에 맞게 바꿀 수 있다.
setlocale() Function
- 월, 일, 요일의 이름을 각 나라에 맞게 변환하여 리턴한다.
Example. setlocale() Function Usage
>>> import locale
>>> from datetime import date
>>> halloween = date(2014, 10, 31)
>>> for lang_country in ['en_us', 'fr_fr', 'de_de', 'es_es', 'is_is',]:
... locale.setlocale(locale.LC_TIME, lang_country)
... halloween.strftime('%A, %B %d')
...
'en_us'
'Friday, October 31'
'fr_fr'
'Vendredi, octobre 31'
'de_de'
'Freitag, Oktober 31'
'es_es'
'viernes, octubre 31'
'is_is'
'föstudagur, október 31'
>>> import locale
>>> names = locale.locale_alias.keys()
>>> good_names = [name for name in names if \
len(name) == 5 and name[2] == '_']
>>> good_names[:5]
['sr_cs', 'de_at', 'nl_nl', 'es_ni', 'sp_yu'] # 5개의 Locale Codes
>>> de = [name for name in good_names if name.startswith('de')]
>>> de
['de_at', 'de_de', 'de_ch', 'de_lu', 'de_be'] # Germany Locale Codes
Alternative Modules
arrow
- 많은 날짜와 시간 함수를 결합하여 간단한 API로 제공한다.
dateutil (URL)
- 대부분의 날짜 포맷을 Parsing하고, 상대적인 날짜와 시간값을 처리한다.
iso8601 (URL)
- ISO 8601 Format에 대한 표준 라이브러리의 부족한 부분을 보충한다.
fleming (URL)
- 표준시간대 함수를 제공한다.
Reference: Introducing Python(처음 시작하는 파이썬) (Bill Lubanovic 저, O'Reilly, 2015