본문 바로가기

python

Do it! 점프 투 파이썬 05-2 모듈

728x90

CMD (명령프롬프트) 실행

 

C:\Users\purplike>cd PycharmProjects\JumpToPython\05-2 Modules

 

C:\Users\purplike\PycharmProjects\JumpToPython\05-2 Modules>dir

 C 드라이브의 볼륨에는 이름이 없습니다.

 볼륨 일련 번호: 2A90-D080

 

 C:\Users\purplike\PycharmProjects\JumpToPython\05-2 Modules 디렉터리

 

2020-04-23  오후 04:24    <DIR>          .

2020-04-23  오후 04:24    <DIR>          ..

2020-04-23  오후 04:05                32 mod1.py

2020-04-23  오후 04:24               869 mod1_import.py

               2개 파일                 901 바이트

               2개 디렉터리  61,615,767,552 바이트 남음

 

C:\Users\purplike\PycharmProjects\JumpToPython\05-2 Modules>python

Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> import mod1

>>> print(mod1.add(3, 4)

... )

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

AttributeError: module 'mod1' has no attribute 'add'

>>> import mod1

>>> print(mod1.add(3, 4))

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

AttributeError: module 'mod1' has no attribute 'add'

>>> import mod1

>>> print(mod1.sum(3, 4))

7

>>>

 

05-3 패키지

패키지(Packages)는 도트(.)를 이용하여 파이썬 모듈을 계층적(디렉터리 구조)으로 관리할 수 있게 해준다. 

패키지 구조로 모듈을 만들면 다른 모듈과 이름이 겹치더라도 더 안전하게 사용할 수 있다.

 

C:\Users\purplike\PycharmProjects\JumpToPython\05-3 Packages>python

Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> import game.sound.echo

>>> game.sound.echo.echo_test()

echo

>>>

 

04 예외 처리

 

'''
try:
except:

'''

'''
print(4/0)

Traceback (most recent call last):
File "C:/Users/Maria/PycharmProjects/JumpToPython/05-4 Exceptions/try_except.py", line 7, in <module>
print(4/0)
ZeroDivisionError: division by zero
'''

try:
print(4/0)
except:
print('except')

try:
print(4 / 0)
except ZeroDivisionError as e:
print(e) # division by zero

try:
print(4 / 1) # 4.0
except ZeroDivisionError as e:
print(e) # division by zero
else:
print('else')

 

try:
with open('filenotfounderrr.txt', 'r') as f:
read = f.read()
except FileNotFoundError as e:
#print(str(e))
print(e)
else:
read = f.read()

# [Errno 2] No such file or directory: 'filenotfounderrr.txt'

 

- END -

 

https://cafe.naver.com/doitstudyroom/20715

728x90