모듈과 패키지

장현빈·2024년 11월 27일

python

목록 보기
4/8

모듈

모듈은 파이썬 코드를 포함하는 파일

# mymod.py
var=10

def myfunc():
    print("hello")
import mymod

print(mymod.var)
mymod.myfunc()

모듈 import

import tkinter
tkinter.widget=tkinter.Label(None, text='I Love Python!')
tkinter.widget.pack()
from tkinter import *
widget=Label(None, text='I love Python!')
widget.pack()
  • 주의: type이 변경되거나 해당 모듈에 맞게 커스텀 될수도 있음에 주의!

calender 모듈

import calendar

dir(calendar)
>>> [x for x in dir(calendar) if 'leap' in x]
['isleap', 'leapdays']
>>> from calendar import isleap
>>> help(isleap)
Help on function isleap in module calendar:

isleap(year)
    Return True for leap years, False for non-leap years.

>>> isleap(2077)
False

random 모듈

  • ramdom(): 0이상 1미만의 숫자중 아무 숫자중 하나를 반환
>>> import random
>>> random.random()
0.2241152171077221
  • randrange(a, b): a이상 b미만의 난수를 반환
>>> random.randrange(1,7)
1
>>> random.randrange(1,7)
4
  • shuffle(): 시퀀스를 랜덤으로 섞는 함수
>>> abc=['a','b','c','d','e']
>>> random.shuffle(abc)
>>> abc
['c', 'e', 'b', 'a', 'd']
>>> random.shuffle(abc)
>>> abc
['d', 'a', 'c', 'e', 'b']

패키지

여러 파이썬 파일과 디렉토리로 구성된 라이브러리를 파이썬에서는 패키지라 부름

pymode
- example
- pymode
  - __init__.py
  - a.py
  - b.py
- setup.py
pymode
- pymode
  - core
    - __init__.py
    - core.py
  - __init__.py
  - a.py
  - b.py
- setup.py
  • 주의점: pymode.core 디렉토리에 __init__.py 파일이 반드시 있어야 함

subprocess

시스템 명령어를 실행하는 방법에는 os.system 혹은 os.spawn등이 있지만 사용방법이 다양하고 유연한 subprocess를 사용하는 것이 가장 일반적

import subprocess

check_output()

# Windows에서 실행되고 있는 프로세스 리스트
output=subprocess.check_output('tasklist')
data=output.decode('cp949')
lines=data.splitlines()

for line in lines:
    print(line)
    
# Mac또는 Linux 에서 실행되고 있는 프로세스 리스트
output=subprocess.check_output(['ps', '-e'])
data=output.decode('utf-8')
lines=data.splitlines()

for line in lines:
    print(line)

run()

리눅스 등에서 다른 프로그램을 실행할때 subprocess 모듈의 run 함수 사용

import subprocess

cmd="your command"
subprocess.run(cmd, shell=True)
OScmd
Windowscmd='dir'
Mac or Linuxcmd='ls'
  • 다른 프로그램을 실행하면서 해당 프로그램이 화면에 출력하는 값을 받아오려면 capture_output=True 사용
import subprocess

cmd="your command"
result=subprocess.run(cmd, capture_output=True, shell=True, encoding='utf-8')
print(result.stdout)

popen()

기본적으로 subprocess.Popen을 사용하여 시스템 명령을 호출하면 백그라운드 프로세스로 실행

proc=subprocess.Popen(...)
try:
    out, errs=proc.communicate(timeout=10)
except subprocess.TimeoutExpired:
    proc.kill()

subprocess.Popen로 생성된 객체에 communicate함수를 사용하면 해당 명령이 종료될때까지 대기. 이때 timeout을 지정가능

import subprocess

cmd="your command to execute program"
process=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, encoding='utf-8')
while True:
    output=process.stdout.readline()
    if output=='' and process.poll() is not None:
        break
    if output:
        print(output.strip())

ls -l를 실행하고 그 결과를 out.txt에 저장

# mac or linux
cmd=['ls', '-l']
result=subprocess.run(cmd, capture_output=True, shell=True, encoding='utf-8')
with open('out.txt', 'w') as f:
    f.write(result.stdout)
# Windows
cmd=['dir']
result=subprocess.run(cmd, capture_output=True, shell=True, encoding='utf-8')
with open('out.txt', 'w') as f:
    f.write(result.stdout)

datetime

from datetime import datetime
# 날짜와 시간을 직접 지정하여 datetime 객체를 생성하는 방법
specific_datetime=datetime(2024, 2, 27, 12, 30)
print(specific_datetime) #결과 2024-02-27 12:30:00
# 두 날짜/시간 사이의 차이를 계산하는 방법
datetime1=datetime(2024,2,27)
datetime2=datetime(2024,3,5)
difference=datetime2-datetime1
print(difference) # 결과 7 days, 0:00:00
# 다양한 형식으로 날짜와 시간을 문자열로 변환하는 방법
current_datetime=datetime.now()
formatted_date=current_datetime.strftime("%B %d, %Y")
print(formatted_date) # 결과 November 27, 2024
# 문자열에서 날짜와 시간을 datetime 객체로 변환하는 방법
date_string="27 February, 2024"
datetime_object=datetime.strptime(date_string, "%d %B, %Y")
print(datetime_object) # 결과 2024-02-27 00:00:00
# 시스템의 현재 시간대를 반영한 날짜와 시간을 가져오는 방법
import pytz
timezone=pytz.timezone('Asia/Seoul')
localized_datetime=datetime.now(timezone)
print(localized_datetime) # 결과 2024-11-27 16:14:01.945106+09:00
# 현재 날짜와 시각을 "yyyy-mm-dd HH:MM:ss" 형식으로 출력

current_datetime=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(current_datetime) # 결과 2024-11-27 16:14:48
# timedelta를 사용하여 날짜에 일, 시간, 분, 초를 더하거나 빼는 방법
from datetime import datetime, timedelta
current_datetime=datetime.now()
one_week_later=current_datetime+timedelta(days=7)
print(one_week_later) # 결과 2024-12-04 16:15:52.573747
profile
인공지능 관련 분야에 관심있습니다.

0개의 댓글