'프로그래밍 언어/파이썬'에 해당되는 글 17건

  1. 2008.03.19 리스트관련 메쏘드
  2. 2008.03.11 간단한 함수들
  3. 2008.03.11 파이썬파일에서 다른 모듈 실행시키기
  4. 2008.02.22 regular exp을 이용한 파일 이름 찾기
  5. 2008.02.21 xml 파서 사용하기
  6. 2008.02.19 파일의 생성, 수정, 접근 시간 알아보기
  7. 2008.02.18 쉘스크립트 수행후 결과 (stdout) 얻어오기

리스트관련 메쏘드

|

append : 리스트 마지막에 추가
             예) L.append(1)
insert : 원하는 위치에 추가
           예) L.insert(1, "aa")
index : 요소검색
           예) L.index(3)  -> 리스트에서 3이라는 요소의 index를 반환한다
count : 요소개수
           예) L.count(3) -> 리스트에서 3이라는 요소의 갯수를 반환
sort : 리스트 정렬, 리스트를 반환하지 않는다
        예) L.sort() -> 오름차순정렬
             L.sort(mycmp()) -> 내가 원하는 정렬방법으로 정렬
             기본은 cmp(a, b)함수를 이용. a < b 이면 음수를 반환하고 a가 앞으로 간다      
             L.sort(reverse=True)
             L.sort(key=int) : 숫자로된 문자열을 숫자로 생각해서 정렬
len : 리스트의 요소의 개수를 반환
            예) len(L)
sorted : 리스트 정렬. 정렬된 리스트를 반환한다
            예) sorted(L)
                 sorted(L, reverse=True)
                 sorted(L, key=int)
reverse : 리스트 정렬, 반대로 정렬. 반환값 없다
reversed : 리스트 역순정렬. 리스트를 반환한다.
remove
pop : 리스트 마지막것을 반환및 리스트에서 삭제
        예) L.pop() : 제일 마지막 요소
             L.pop(0) : 제일 앞요소
extend : 리스트추가

* 참고
   같은종류의 기본 자료형 배열을 생성할경우
   from array import *
   a = array ('i', range(10))
   a를 리스트로 자유롭게 사용가능

And

간단한 함수들

|

str : 어떤 객체를 문자열 표현으로 변환해준다
      예) str(12345)  -> '12345'

type : 자료형을 확인한다
       예) a = 'dynamic'
           type(a) -> <type 'str'>

eval : 문자열로 된 파이썬식을 실행한다 (식만을 수행한다)
       예) a = 1
           a = eval ('a + 4')
           a  -> 5

exec : 문자열로 된 문을 수행한다 (여러개의 문이라도 가능하다 ''' 로 묶어준다)
       예) a = 5
           exec 'a = a+4'
           a -> 9

compile : 문자열을 파이썬코드로 변환한다
          compile (string, filename, kind)
          string : 코드 문자열
          filename : 코드 문자열이 저장된 파일명 (파일에서 읽혀지지 않았으면 <string>으로 하자)
          kind : exec 여러개의 문일경우
                 eval 하나의 식일경우
                 single 하나의 대화식문

raw_input ('name?') : 키보드로부터 문자열을 입력받는다
          예) name = raw_input ('이름')

len : 문자열의 길이를 반환한다
      예) len(a) -> 9

getrefcount : 레퍼런스 카운트 얻기
              예) import sys
                  sys.getrefcount(a) -> 2
              실제 레퍼런스 카운트보다 하나가 많다 (getrefcount함수가 하나를 참조하기때문에)

id : 객체의 주소 식별
     id(a) -> 22675984

enumerate : 요소의 값과 인덱스 2개를 반환한다
            예) L = ['a','b','c']
                for k, alpha in enumerate (L):
                    print k, alpha

range : 숫자들의 리스트로 반환
        예) range(4) -> [0,1,2,3]
            range(1,11) -> [1,2,3,.....,10]

divmod : 나머지와 몫을 동시에 계산
         예) divmod(5,3) -> (1, 2)

str : print문과 동일한 출력 결과
         예) str(f)

repr : 변수이름만 출력시에 나오는 결과
         예) repr(f)

vars(), locals() : 현재 지역변수와 변수들을 사전형식으로 반환

dir() : 지역적으로 사용가능한 이름 리스트 얻기

And

파이썬파일에서 다른 모듈 실행시키기

|
pytho실행시 기본 환경설정
  PATH=파이썬실행파일의 경로 (보통 /usr/local/bin)
  PYTHONPATH=파이썬 모듈을 찾을 경로 (import 되는 모듈들은 시스템 디렉토리, 현재 작업디렉토리 이경로에 
  서 찾는다)
  PYTHONSTARTUP=파이썬 실행시 자동으로 수항핼 스크립트들의 나타낸다
      예) .pythonrc 파일 -> import os, sys 
           PYTHONSTARTUP=$HOME/.pythonrc

스크립트식으로 실행하기위해서
 #!/usr/bin/python
 여기가 원하는 버전이 아닐경우 해당 버전으로 이어주자. (which python하면 현재 python의 바이너리의 실행위
 치를 알수 있다)
 #!/usr/bin/env python : 시스템이 알아서 경로를 찾아서 수행시켜준다

파이썬 실행중에 path추가시
 import sys
 sys.path
 sys.path.append='/X/X'

import로 수행하기
  import modfile  #모듈이름은 modfile.py이지만 import시 뒤에 py는 빼준다

모듈의 도움말 보기
  import sys
  help(sys)
And

regular exp을 이용한 파일 이름 찾기

|
import glob

glob.glob ("/home/my/*.static.*")
을 하면 해당 reg exp에 해당하는 리스트를 반환한다.
And

xml 파서 사용하기

|
from xml.dom.minidom import parse, parseString
dom = parse(xml파일 경로명)
groups = dom.getElementsByTagName("group")  // <group name="xx"> 같은 group으로 묶인 애들의 리스트를 얻어온다

for group in groups:
    name = group.attributes["name"].value         // group에 속한 name attribute의 value값을 갖어온다
    properties = group.getElementsByTagName("property") // 해당 그룹 하위의 property군들의 정보를 얻어온다.
   for property in properties:
        value = property.attributes["value"].value
And

파일의 생성, 수정, 접근 시간 알아보기

|
One is the number
of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer
or a floating point number (to represent fractions of seconds).
The Epoch is system-defined; on Unix, it is generally January 1st, 1970

import os
os.path.getctime(패스)
os.path.getmtime(패스)
.. .



getatime( path)

Return the time of last access of path. The return value is a number giving the number of seconds since the epoch (see the time module). Raise os.error if the file does not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If os.stat_float_times() returns True, the result is a floating point number.

getmtime( path)

Return the time of last modification of path. The return value is a number giving the number of seconds since the epoch (see the time module). Raise os.error if the file does not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If os.stat_float_times() returns True, the result is a floating point number.

getctime( path)

Return the time of creation of path. The return value is a number giving the number of seconds since the epoch (see the time module). Raise os.error if the file does not exist or is inaccessible. New in version 2.3.

getsize( path)

Return the size, in bytes, of path. Raise os.error if the file does not exist or is inaccessible. New in version 1.5.2.
And

쉘스크립트 수행후 결과 (stdout) 얻어오기

|
import os
stdin, stdout = os.popen2('du -sh')
print stdout.redlines()
stdin.close()
stdout.close()


하면 결과실행한 값을 알수 있다.
또는 
temp = stdout.readlines() 하면 리스트 형태로 temp리스트에 결과값이 저장된다.
이것은 명령어 입력값을 바꾸고 싶을때 사용한다


단순히 실행한 파일의 stdout만을 가져오고싶다면
import commands
output = commands.getoutput(cmd)   ''' output을 가져온다
status = commands.getstatus(file)     ''' return output of "ls -ld <file>" in a string
statusoutput = commands.getstatusoutput(cmd) ''' return (status, ouput)of executing cmd in a shell

이것은 다음을 실행시키는것과 같다
      pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
      text = pipe.read()
      sts = pipe.close()
And
prev | 1 | 2 | next