반응형



+ 쉘 커맨드 실행하기.

1. os.system 구문을 이용해 명령 실행 하기
import os
import sys
os.system ('ls -al | grep "user")

// pipe command is available
위와 같이 단순히 명령 실행을 위해 사용시에는 문제가 없으나,
결과값을 특정 변수에 저장하는 목적으로 사용하기에는 적합하지 않다.
(명령 실행 결과의 성공 유무를 리턴하기 때문에…)
따라서 위의 단점을 보완할 수 있는 방법이 바로 subprocess 이다.

2. subprocess 이용하여 명령 실행하기
먼저 os.system과 같이 단순히 “실행”만 시킬 때는 “call” 메서드를 이용하면된다.

import subprocess
subprocess.call ('ls -al', shell=True)
그러나 특정 명령 수행 결과를 바탕으로 if 조건문을 걸때에는 call이 아닌 check_ouput을 이용해야 한다.

예를들어 특정 파일 실행결과가 “AAA” 혹은 “BBB”라고 가정해보자.
“AAA” 일 경우 “123”을 출력하고 “BBB”일 때 “456”을 출력하려면 다음과 같이 코드를 작성하면 된다

import subprocess
result = subprocess.check_output ('./program' , shell=True)
if result == 'AAA' :
  print "123"
elif result == 'BBB' :
  print "456"
위와 같이 check_output 메서드를 사용하면 해당 실행 결과를 스트링값으로 리턴해주기 때문에

실제 실행결과값을 바탕으로 조건 구문을 사용할 수 있게 된다.

 


'Python' 카테고리의 다른 글

Python 데이터 저장/로딩 Pickle  (0) 2018.04.25
Python 커맨드라인 파싱  (0) 2018.04.17
Python JSON 사용하기  (0) 2018.04.10
Python 외부 모듈사용.time,string,random, try except  (0) 2018.04.09
Python 강좌7 클래스  (0) 2018.03.27
반응형





+JSON
기본으로 설치되어 있다.
import json

-JSON 인코딩
customer={ 'id':111, 'name':'james',
    'history':[ {'date':'2015-01-01', 'item':'iphome'}, {'date':'2016-01-01', 'item':'android'}]
}
jsonString = json.dumps(customer)    # JSON 스트링으로 변환

출력
print(jsonString)

보기 좋게 출력하려면 인코딩시 indent 추가
jsonString = json.dumps(customer, indent=4)

-JSON 디코딩
JSON 스트링을 Python 객체로
dict = json.loads(jsonString)
dict['name']
dict['history'][0]['date']
for h in dict['history']:
    print(h['date'], h['item'])

 


'Python' 카테고리의 다른 글

Python 커맨드라인 파싱  (0) 2018.04.17
Python 쉘 커맨드 실행  (0) 2018.04.12
Python 외부 모듈사용.time,string,random, try except  (0) 2018.04.09
Python 강좌7 클래스  (0) 2018.03.27
Python 강좌6 tuple, set, dictionary  (0) 2018.03.21
반응형




모듈 Module


+ 외부 모듈 가져오기 (import)
import시 찾는 경로를 알기 위해서는 아래와 같이 path를 찾아본다.
import sys
sys.path
PATH 추가
sys.path.insert(0, ‘/home/…’)   첫 번째 path에 추가한다.

import 모듈      ; 모듈 전체 가져오기. 사용시 모듈.변수 등으로 사용.
or
from 모듈 import 변수나 함수  ; 모듈의 특정 부분만 가져오기.
import한 모듈을 더 이상 사용 안할 경우
del 모듈
다시 불러오기
reload 모듈

import math
dir(math)          # math에 정의되어 있는 함수, 변수등을 확인.
math.sin(90)
math.row(2,10)
math.pi

+ 모듈의 정의
arithmetic.py라고 파일이름을 만들어 여러가지 함수들을 만든다.

import arithmetic
dir(arithmetic)
arithmetic.plus(1,2)
arithmetic.mul(300,400)

현재 경로에 존재하지 않으면?
폴더 지정도 가능. 현재폴더 기준. mylib 폴더내에 arithmetic.py가 있다면...
from mylib.arithmetic import *


from arithmetic import plus     # 해당 파일의 특정 함수만 로딩.
plus(100,200)

from arithmetic import *     # 해당 파일에 있는 모든 함수 사용 가능.





+string 모듈

import string
string.captialize('python')
'Python'
string.replace('simple', 'i', 'a')
'sample'
string.split('break into words')
['break', 'into', 'words']

+webbrowser 모듈
import webbrowser
url='http://google.com'
webbrowser.open(url)

+random
import random
random.random()
0이상 1미만 소수
random.randrange(1,7)
1~6까지 정수.









+ with as
; try~finally 같은 역할.
특정 블록을 벗어날때 항상 처리되어야 할 것이 자동화 처리.
with open('filename', 'w') as f:
     f.write(something);
close()가 없어도 자동 처리.



+ 시간 time, date 날짜
import time
time.time()     ; 19700101이후누적 시간 (초). 소수점이하 포함.
time.ctime()    ;    Sun Oct 11 12:00:50 2015
time.gmtime()
time.localtime()

time.sleep(sec) ; millisec를 하려면, sec/1000.0으로 해줘야 함.


dir(time)    ; 모듈의 내장 함수 목록 조회.



+try, except
try… except  예외 처리.
자바와 c++에서는 try, catch를 사용하고, 예외 발생시 throw를 사용.
파이썬은 try, except를 사용하고, raise를 사용.

try:
     to do...
except:
     ignore....



if size<0:
    raise ValueError(‘number must be non-negative!’)



+try ~ except

try:
    구문
except <예외 종류>:
    예외 처리

try:
    a=10/0
except ZeroDivisionError:        # 잡을 예외
    print('divede by zero.')

try:
    a=int( input('input number:'))
except ValueError:
    print('invalid number!')
except ZeroDivisionError:            # 더 있으면 아래 계속 추가 가능.
    print('divide by zero!')

except (ValueError, ZeroDivisionError):        # 복수개를 한 번에 처리 가능.


+ else
try:
    ...
 except ...:
        ...
else:
    예외가 발생하지 않을 경우.

+ finally

finally:
    무조건 실행되는 영역

+raise
예외 발생

try:
    ...
    if a<=0 or b<=0:
        raise ArithmeticError('message...')
    except ArithmeticError as e:
        print( e.args[0] )
에러 메시지를 받아 출력...





+실행프로그램으로 현재 코드가 실행되는지 확인. (외부 임포트의 경우는 아래 코드가 실행되지 않음.)
if __name__==‘__main__’:
    print(…)





'Python' 카테고리의 다른 글

Python 쉘 커맨드 실행  (0) 2018.04.12
Python JSON 사용하기  (0) 2018.04.10
Python 강좌7 클래스  (0) 2018.03.27
Python 강좌6 tuple, set, dictionary  (0) 2018.03.21
Python 강좌5 List  (0) 2018.03.20

+ Recent posts