지구정복
[Python] 3/10 | import 사용하기(함수안에서import, 별칭사용), 패키지, 중요모듈사용(sys, os, call, calendar, time) 본문
[Python] 3/10 | import 사용하기(함수안에서import, 별칭사용), 패키지, 중요모듈사용(sys, os, call, calendar, time)
noohhee 2021. 3. 10. 12:011. 다른 모듈 가져와서 사용(import)
다른 모듈의 메서드를 가져와서 사용해보자.
이때 mod1을 import한다는 것은 자바처럼 클래스를 불러오는 것이 아닌 네임스페이스(이름공간)에 저장하고 사용하는 것이다.
또한 import하는 모듈을 직접실행할 경우 __name__ == "__main"": 을 써주면 된다. 그러면 다른 모듈에서 import할때는 해당 코드는 실행되지 않는다.
-mod1
def add( a, b ):
return a + b
def sub( a, b ):
return a - b
#실행부분
#독립 실행할 때 시작부분
#시작부분을 정의하고 싶을 때 아래처럼
if __name__ == "__main__":
print( 'mod1 : ', add( 10, 20 ) )
#하지만 다른 모듈에서 mod1을 실행시키면 위 구문은 실행되지 않는다.
-main
import mod1 #모듈 통쨰로 가져오기
print( dir( mod1) )
print( mod1.add( 3, 4 ) )
혹은 아래와같이 mod1의 특정 메서드만 가져올 수 있다.
from mod1 import add #해당모듈에서 특정 함수만 가져오기
print( add( 3, 4 ) )
모듈이 저장되어 있는 디렉터리에 가서 해당 mod1.module을 복사해서 python39 > Lib > site-package안에 붙여넣는다.
그리고 이클립스 > preperence > pydev > interpreters > python interpreter > Libraries > New Folder > lib 폴더 다시 불러오기 > Apply
함수 안에서 모듈 import하기
def loadMathMod():
print( "import math" )
import math
#from math import __name__ 도 가능하다.
print( dir( math) )
loadMathMod()
import모듈 별칭으로 사용하기
import xml.sax.handler as handler
print( xml.sax.handler )
print( handler )
2. 패키지 사용하기
패키지
파이썬에서는 여러 가지 모듈과 패키지를 제공하는데 이는 Lib이라는 하위 디렉터리에 저장돼 있다.
각 디렉터리마다 __init__.py가 있는데 일반 디렉터리에는 해당 파일이 없고 패키지의 디렉터리에는 해당 파일이 존재한다.
또한 특정 패키지의 하위 패키지를 import할 때는 . 으로 들어간다.
프로젝트 오른쪽클릭 > pydev패키지 > name지정 > 만들기
game이라는 패키지만들고 game.sound와 game.graphic 하위 패키지를 또 만들어준다.


graphic패키지 안에 echo, screen 모듈을 만들고 아래와 같이 코딩한다.
-echo
def echo_test() :
print( 'echo_test' )
-screen
def screen_test() :
print( 'screen_test' )
이를 불러다사용해보자. 프로젝트에서 새로운 모듈을 만든다.
-mod2.py
import game.graphic.screen as screen
print( dir( screen) )
screen.screen_test()
이번에는 함수에 접근해보자.
-mod3.py
from game.graphic import screen
print( dir( screen ) )
screen.screen_test()
만일 같은 패키지에서 현재 디렉터리에 있는 모듈이나 부모 디렉터리에 있는 모듈을 import할 때는
.(현재 디렉터리) 또는 ..(부모 디렉터리)를 사용한다.
from .. import formats
from . import formats
3. 중요모듈 사용하기
1. sys 모듈 사용
argument를 주려면 화면 오른쪽클릭 > run > run configuration > Arguments > Program arguments에 1 2 를 작성

#sys 모듈 사용
import sys
#print( dir( sys) )
#어떤 파일을 실행하고 있는지 확인하고 실행시 argument를 출력
print( sys.argv )
argv = sys.argv
print( argv[0] )
print( argv[1] )
print( argv[2] )

sys의 각종 정보 출력
#sys 모듈 사용
import sys
#sys 버전 정보 확인
print( sys.version )
print( sys.version_info )
print( sys.api_version )
#sys 경로의 파일 및 폴더 확인
print( sys.path )
#sys 경로에 폴더 추가
sys.path.append( 'c:/python/mymodule' )
print( sys.path )
#sys 경로에 폴더 제거
sys.path.remove( 'c:/python/mymodule' )
print( sys.path )


프로그렘 강제 종료
import sys
#프로그램 강제종료시키기
print( '시작' )
sys.exit()
print( '끝' )

2. os 사용하기
import os
#시스템 환경변수에 데이터들 출력
print( os.environ )
#특정 환경변수 데이터만 출력하기
print( os.environ['PATH'])

작업경로 출력 및 변경
import os
#os모듈의 메서드사용하기
#작업경로 출력
print( os.getcwd() )
#작업경로 변경하기
os.chdir( 'c:/python' )
print( os.getcwd() )

현재 디렉터리의 파일 목록 출력하기
한글은 깨져서나온다.
import os
os.system( 'dir' )

핑 확인하기
import os
os.system( 'ping Localhost' )

3. call 사용하기
계산기 실행하기
from subprocess import call
call( 'c:/windows/system32/calc.exe' )

4. calendar 사용
import calendar
print( calendar.calendar( 2021 ) )

특정 달만 출력하기
import calendar
calendar.prmonth( 2021, 4 )

특정 요일 출력하기
import calendar
#월요일이 0이다.
print( calendar.weekday( 2021, 4, 7 ) )

특정 달의 마지막 날 출력
import calendar
#1일의 요일과 마지막 날 일 정보 출력
print( calendar.monthrange( 2021, 4 ) )

5. time 사용하기
import time
#unix date라는 timestamp가 출력된다.
print( time.time() )

실제 시간 확인하기
import time
print( time.localtime() )
t = time.localtime()
print( t.tm_year )
print( t.tm_mon )

시간을 문자열화해서 출력하기
import time
print( time.asctime( time.localtime()))

날짜형식 지정해서 출력하기
import time
print( time.strftime( '%Y-%m-%d', time.localtime() ) )

'데이터 엔지니어링 정복 > Python' 카테고리의 다른 글
[Python] 3/12 | 파이썬과 데이터베이스 연동(python에 MariaDB설치, 연동, statement기법 사용, preparedstatement기법 사용, select문 사용) (0) | 2021.03.12 |
---|---|
[Python] 3/11 | Math모듈, Random모듈, 파일시스템, 파일입출력(우편번호검색) (0) | 2021.03.11 |
[Python] 3/9 | 상속과 예외처리 (0) | 2021.03.09 |
[Python] 3/3 | 기본문법 (0) | 2021.03.03 |
[Python] 3/2 | 이클립스에서 pydev 사용하기 (0) | 2021.03.02 |