레이블이 Python인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Python인 게시물을 표시합니다. 모든 게시물 표시

compiled python No module named _sqlite3

if your python2.7 occured error and you compiled new python on linux,


you can fast resolve this error.

how to resolve its error below.

1) find _sqlite3.so file

$ find / -name _sqlite.so 2> /dev/null

2) copy _sqlite3.so file to your PYTHON_DYNAMIC_LIBRARY_PATH
 - my PYTHON_DYNAMIC_LIBRARY_PATH is /usr/local/lib/python2.7/lib-dynload

$ cp /usr/lib64/python2.7/lib-dynload/_sqlite3.so /usr/local/lib/python2.7/lib-dynload

3) then you can import sqlite3

python command timeout (Advanced)

python에서 command 실행시 타임아웃 설정 (Advanced)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import subprocess as sp

class ExecuteFile:
    class TimeoutException(Exception):
        pass

    # timeout 커맨드실행
    @staticmethod
    def execute(cmd, errorKeyword=['error', 'fail', 'bad'], timeout=10):
        #pdb.set_trace()
        #popen = sp.Popen(cmd.split(), stderr=sp.STDOUT, stdout=sp.PIPE, env=os.environ)
        popen = sp.Popen(cmd, shell=True, stderr=sp.STDOUT, stdout=sp.PIPE, env=os.environ)

        # timeout 처리
        sTime = time.time()
        try:
            while True:
                if popen.poll() is not None:
                    break

                if time.time()-sTime > timeout:
                    raise ExecuteFile.TimeoutException

                time.sleep(0.1)

        except ExecuteFile.TimeoutException as e:
            popen.kill()

            return False, cmd, 'TimeoutException'

        # 에러 keyword 처리
        stdout = popen.stdout.read()

        for keyword in errorKeyword:
            if keyword in stdout:
                return False, cmd, stdout


        return True, cmd, 'SUCCESS'

how to install compiling python with ssl

ㅇ 아래 버전을 설치하였습니다.
- python2.7.15
- openssl1.0.2r


1. python설치 (ssl가능 세팅)
* 루트로 진행
1) python을 내려받고 압축을 푼다.

2) Modules/Setup.dist 를 편집
   2.1) SSL 로 찾기하면
         SSL=/usr/local/ssl 부터 총 4줄이 주석 처리되어 있음. 해제
         * python을 make했을때 ssl관련하여 컴파일 오류가 뜬다면 openssl경로를
           여기에 넣어 주어야 함.
           (허나 필자는 무식하게 Makefile을 변경하여 컴파일 완료하였음.)

3) $> ./configure (설정은 재량껏)
4) $> make
  4.1) 여기서 ssl관련하여 컴파일에러가 난다면 2.1)로 다시가서 설정하고
        다시 진행하는 방법과 지금 필자가 서술하는 방법이 있다. 후자를 서술하겠음.
  4.2) Makefile을 편집
       SSL=/usr/local/ssl 이란곳을 찾아 openssl경로로 바꾸어준다.
5) $> make install

2. openssl 설치
  1) openssl을 내려받고 압축을 푼다.
  2) $> Configure linux-x86_64 shared --prefix=/usr/local/openssl   (64비트 가정)
  3) $> make
  4) $> make install
  5) $> openssl version
     * 쉐어드 라이브러리 에러가 난다면 LD_LIBARY_PATH에
       openssl/lib 경로를 추가해준다.

python function timeout decorator

it's function's timeout decorator on python



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from functools import wraps
import time
import signal
import errno

class TimeoutError(Exception):
    pass

def funcTimeout(timeout=30):
        def decorator(func):

                def handleFuncTimeout(signum, frame):
                        raise TimeoutError(os.strerror(errno.ETIME))

                @wraps(func)
                def wrapper(*args, **kwargs):
                        #print '[%d]wrapper START' % id
                        sTime = time.time()

                        signal.signal(signal.SIGALRM, handleFuncTimeout)
                        signal.alarm(timeout)

                        try:
                                result = func(*args, **kwargs)
                        finally:
                                signal.alarm(0)

                        #print '[%d]wrapper END(elapseTime=%d)' % (id, time.time()-sTime)

                        return result

                return wrapper

        return decorator


#DIRECTIONS
@funcTimeout(3)
def func():
    print 'func() start'
    time.sleep(5)
    print 'func() end'

func()

python threading.Thread생성시 function argument 사용 주의점

threading.Thread 생성시 function argument 사용할때

name을 구분해주지 않으면 같은 name이 재시도 되지 않는다.
(name을 구분해야 제대로 돌아간다는말)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// 1) 안 좋은 예

def func():
  pass

for i in range(3):
  th = threading.Thread(func())
  th.start()


// 2) 좋은 예

def func():
  pass

for i in range(3):
  thName = 't%d' % i
  th = threading.Thread(func(), name=thName)
  th.start()

convert (unicode <-> euc-kr)

python 2.x에 unicode는 언제봐도 항상 어려운거 같다.

example로 여기다가 남기겠음.

#-*- coding: utf-8 -*-

# utf-8 -> euckr
s1 = unicode('파이썬2.x 유니코드 정말 싫다!!', 'utf-8')
s2 = s1.encode('euc-kr')
print s2

# euckr -> utf-8
s3 = unicode(s2, 'euc-kr')
s4 = s1.encode('utf-8')
print s4

how to install django on cygwin

Cygwin is very restrictive when installs packages.

I needed to install django on cygwin.

I will introduce to install django on cygwin.

following is how to install django 1.8.7 with python 2.7 on cygwin 2.3.0 x86_64

1) install cygwin
   recommending category packages are admin, Base, Database, Debug, Devel, Editors, Interpreters, Libs, Python, Math, Security, System, Util, Web

2) get the django source https://www.djangoproject.com/download/1.8.7/tarball/

3) extract Django-1.8.7.tar.gz

4) $ cd Django-1.8.7
    $ python setup.py build

5) $ python setup.py install

6) enjoy the django

django error 'dict' object has no attribute 'META'

django 에러

symptom:
'dict' object has no attribute 'META'
Request Method:GET
Request URL:http://128.199.227.215:8000/tag/naver/
Django Version:1.8.4
Exception Type:AttributeError
Exception Value:
'dict' object has no attribute 'META'
Exception Location:/usr/local/lib/python2.7/site-packages/django/template/context_processors.py in debug, line 43
Python Executable:/usr/local/bin/python
Python Version:2.7.10
Python Path:
['/home/django/easy',
 '/usr/local/lib/python27.zip',
 '/usr/local/lib/python2.7',
 '/usr/local/lib/python2.7/plat-linux2',
 '/usr/local/lib/python2.7/lib-tk',
 '/usr/local/lib/python2.7/lib-old',
 '/usr/local/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/site-packages']

solution:
뷰쪽(views.py)에 RequestContext 아규먼트가 제대로 들어갔는지 확인한다.

parsing xml on python. unknown encoding

symptom:
SOAP 통신 서버 시뮬레이터에 xml 파서인 ElementTree에 fromString 메서드에서

"ExpatError: unknown encoding" 에러를 발생시켰다.

--------------------------------------------------------------------------------------
  File "/usr/local/lib/python2.6/SocketServer.py", line 322, in finish_request
  File "khubOiServerOri.py", line 320, in response
  File "/usr/local/lib/python2.6/xml/etree/ElementTree.py", line 1245, in feed
    method()
  File "khubOiServerOri.py", line 125, in do_POST
  File "khubOiServerOri.py", line 177, in recvHandler
  File "/usr/local/lib/python2.6/BaseHTTPServer.py", line 329, in handle
    self.handle_one_request()
    self._parser.Parse(data, 0)
  File "/usr/local/lib/python2.6/BaseHTTPServer.py", line 323, in handle_one_request
192.168.151.30 - - [19/Oct/2015 14:14:08] "POST / HTTP/1.1" 200 -
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/local/lib/python2.6/SocketServer.py", line 617, in __init__
    reqDic = parseOi.parseOi(raw)
  File "/home/pis/SIM/lib/parseOi.py", line 37, in parseOi
    root = ET.fromstring(uRawData)
    method()
    rspData = self.response(paramDic)
ExpatError: unknown encoding: line 1, column 30
--------------------------------------------------------------------------------------

클라이언트는 euc-kr세팅으로 SOAP 통신을 하였고

서버 시뮬레이터에서는 UTF-8 세팅이 기본이였다.

모든것을 다 해보진 않았지만 ElementTree에서는 UTF-8이 기본세팅이기에

euc-kr 세팅으로는 파싱이 안되는걸로 추측하고 있다.

solution:
들어오는 스트링을 utf-8로 변환하고 xml header에 encoding을 utf-8로 세팅한다.
1) before
    root = ET.fromstring(rawData)

2) after
    uRawData = unicode(rawData, 'euc-kr').encode('utf-8')

    uRawData = uRawData.replace('euc-kr','utf-8')

    root = ET.fromstring(uRawData)

pip error ImportError: cannot import name HTTPSHandler

It'a way to use ssl by compiling python 2.7


it's reason that no openssl, openssl-devel in python with Centos
( if you using ubuntu, maybe no libssl, libssl-dev )

1. yum install openssl openssl-devel -y

2. Get the Python source in http://www.python.org

3. Extract Python source

4. open "Modules/Setup.dist" by vi
   vi Modules/Setup.dist

5. search "SSL"

6. you can find it as follow
#SSL=/usr/local/ssl
#_ssl _ssl.c \
#        -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
#        -L$(SSL)/lib -lssl -lcrypto

remove '#'

7. Compile the Python source
./configure
make
make install

8. enjoy it

python simple config library

* Python simple config library code
----------------------------------------------------------------------------------
from ConfigParser import SafeConfigParser

class UserConfigParser:
    def __init__(self):
        self.configParser = SafeConfigParser()
        self.sectionName = ''

    # 컨피그 파일을 가져온다
    def getConfigFile(self, fileName):
        self.configParser.read(fileName)

    # "[String]" 형태의 section(subject)를 가져온다.
    def getSection(self, sectionName):
        self.sectionName = sectionName

    def getBoolField(self, fieldName):
        if self.sectionName == '':
            return None
        elif fieldName == '':
            return None

        rawValue = self.configParser.get(self.sectionName, fieldName)
        value = rawValue.rsplit('#',1)[0].strip()

        if value == 'false' or value == 'False' or value == 'FALSE':
            return False
        elif value == 'true' or value == 'True' or value == 'TRUE':
            return True
        else:
            return False

    def getStringField(self, fieldName):
        if self.sectionName == '':
            return None
        elif fieldName == '':
            return None

        rawValue = self.configParser.get(self.sectionName, fieldName)
        value = rawValue.rsplit('#',1)[0].strip()

        if value[0] == "\'" or value[0] == "\"": # 최초 스트링에 \' \" 값을 제거
            value = value[1:]
        if value[-1] == "\'" or value[-1] == "\"": # 마지막 스트링에 \' \" 값을 제거
            value = value[:-1]

        return value
----------------------------------------------------------------------------------


* CONFIG FILE CONTENT (config.cfg)
----------------------------------------------------------------------------------
[SUBJECT]
NAME = JinheeNoh
CITY = Seoul
----------------------------------------------------------------------------------


* Usage
----------------------------------------------------------------------------------
config = UserConfigParser()

config.getConfigFile('./config.cfg')
config.getSection('SUBJECT')
name = config.getStringField('NAME')
city = config.getStringField('CITY')
----------------------------------------------------------------------------------

simple http server in python

CLIENT
-------------------------------------------------------------------------------------------
#-*- coding:euc-kr -*-
import httplib, urllib
import sys

def conn(msg):
    params = urllib.urlencode({'msg':msg})
    headers = {"Content-type": "application/x-www-form-urlencoded",
                "Accept": "text/xml"}
    conn = httplib.HTTPConnection('127.0.0.1','10001')
    conn.request("GET", '/', params, headers)
    rsp = conn.getresponse()
    print rsp.read()
    print 'END'

if __name__ == '__main__':
    if len(sys.argv) == 2:
        msg = sys.argv[1]
        conn(msg)
    else:
        print 'Invalid args'
-------------------------------------------------------------------------------------------



SERVER
-------------------------------------------------------------------------------------------
#-*- coding:euc-kr -*-
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ForkingMixIn
from urllib import unquote_plus

class ForkingHTTPServer(ForkingMixIn, HTTPServer):
    pass

class MyHTTPHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        length = int(self.headers.getheader('content-length'))
        raw = self.rfile.read(length)

        msg = unquote_plus(raw.split('=')[1])

        print msg

        self.send_response(200)
        self.send_header('Content-type', 'text/xml')
        self.send_header('Content-length', str(len(msg)))
        self.end_headers()

        self.wfile.write(msg)
        self.wfile.close()

if __name__ == '__main__':
    print 'START ForkingHTTPServer'

    server = ForkingHTTPServer(('127.0.0.1',10001), MyHTTPHandler)
    server.serve_forever()
-------------------------------------------------------------------------------------------

python command timeout

python에서 command 실행시 타임아웃 설정

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import subprocess

'''
command 실행시 타임아웃을 걸고 stdout은 PIPE로 출력하여
'RESULT'가 검색된다면 'RESULT' 아래 라인을 반환
'''

def executeCmdTimeout( strCmd, timeout=60 ):
        # subprocess.Popen은 명령어는 실행시 fork하여 실행됨.
        p = subprocess.Popen( strCmd, stdout=subprocess.PIPE, shell=True )
        startTime = time.time()

        while p.poll() is None:
                time.sleep(0.1) # 100ms 마다 폴링하여 시간 확인

                nowTime = time.time()
                if nowTime - startTime &gt; timeout: # 타임아웃이 되었다면
                        p.kill()
                        return ''

        lines = p.stdout.read().split('\n') # line단위로 스플릿

        # stdout에 RESULT라는 스트링이 존재한다면 바로 아래 라인을 반환
        idx = 0
        while idx < len(lines):
                if lines[idx][:len('RESULT')] == 'RESULT':
                        return lines[idx+1:]

                idx += 1

        return None


>>>> advanced 코드글 링크

Python ctypes.c_char_p의 할당 매커니즘

python에서 c 라이브러리를 바인딩하기 위한 방법으로 ctypes를 쓰게 된다.

c_char_p는 c 라이브러리의 char*를 python으로 가져오는 오브젝트이다.

c_char_p는 사용된 문자열 주소값을 참조하는걸로 추측된다.

c_char_p변수 두개를 같은 문자열로 선언하면

같은 주소값을 가르킨다.

아래 파이썬 콘솔에서 입력한 코드를 참고하여 설명하겠다.

>>> from ctypes import *
>>>
>>> string1 = c_char_p(10)
>>> string2 = c_char_p(10)

>>> print string1
c_char_p(10)

>>> string1.value = ''
>>> string2.value = ''

>>> print string1
c_char_p(4294250668)

>>> print string2
c_char_p(4294250668)

고로 스트링의 동적할당을 위해선

create_string_buffer() 를 사용하도록 한다.

sqlite "no such column" error

python으로 sqlite3를 쓰는 도중 에러가 발생했다.

"no such column"

뭐지? 컬럼이 없다?

엎어치고 매치고 결국엔 쿼리문 스트링을 출력해보니

아래처럼 from절과 컬럼이 붙어 있는것이 아닌가?

"select col1, col2from table"

정말 바보같다.

결론은 no such 에러 구문이 발생됬다면 쿼리의 syntax 에러부분을

먼저 확인해야할 듯하다.


QT designer와 PySide연동하기

QT designer와 PySide를 연동하여 시그널 매핑까지 하는 샘플코드이다.

ui 파일을 불러와 시그널까지 매핑하는 부분을 참고할 수 있는 사이트가 별로 없어

상당히 많이 헤맸다.

# -*- coding: utf-8 -*-
import sys
from PySide import QtCore
from PySide import QtGui
from PySide import QtUiTools # QT designer의 UI파일을 로드할 수 있게 해주는 라이브러리

class Dialog(QtGui.QDialog):
  def __init__(self, parent=None):
    super(PosSimDialog, self).__init__(parent)
    loader = QtUiTools.QUiLoader();
    file = QtCore.QFile("pos.ui")
    file.open(QtCore.QFile.ReadOnly)
    self.ui = loader.load(file, self)
    file.close()

    # mapping signal
    self.ui.btn_ok.clicked.connect(self.ok) # 디자이너에 btn_ok인 버튼이 클릭시 실행될 메소드를 ok()로 지정한다.

  def show(self):
    self.ui.show()
    self.ui.open()

  def ok(self): # btn_ok버튼 클릭시 실행될 코드 부분
    pass

if __name__ == "__main__":
  app = QtGui.QApplication(sys.argv)
  dlg = Dialog()
  dlg.show()
  app.exec_()

C와 Python 소켓 데이터 연동

C와 Python 소켓 데이터 연동

C에서 소켓으로 스트럭쳐 데이터를 send하고
Python에서 소켓으로 데이터를 받아 스트럭쳐의 밸류값을 recv, 다시 데이터를 send하는 에코 서버 로직을 구현해 보았다.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Python server simulator
# 133 사이즈의 데이터를 소켓으로 recv하고 받았던 곳으로 다시 준다.

# struct.unpack시에 '='인자를 포함함으로써 padding byte를 제거 하고 C에서
# "#pragma pack(1)"과 같은 역할을 하게 한다.

dataFormat = '='         

dataFormat += '20s'  # 스트링 20 byte
dataFormat += '4s'
dataFormat += '2s'
dataFormat += '2s'
dataFormat += '10s'
dataFormat += 'c'      # char 1byte
dataFormat += '2s'
dataFormat += '38s'
dataFormat += 'c'
dataFormat += 'c'
dataFormat += '2s'
dataFormat += '2s'
dataFormat += '9s'
dataFormat += '8s'
dataFormat += '8s'
dataFormat += '6s'
dataFormat += '6s'
dataFormat += '7s'
dataFormat += '4s'

stNiceCardInfoReq = struct.Struct( dataFormat )
# 스트럭쳐 구조에 대한 정의를 Struct() 매개변수로 돌려준다
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 8888))
sock.listen(5)
while 1:
    cli_sock, addr = sock.accept()
    recvData = cli_sock.recv(133)

    for str in data:
        print str
    rst = cli_sock.send(recvData[:133])
    print "send(%d)"%rst

sock.close()

# 받은 데이터 133 사이즈 패킷을 dataFormat 형식으로 마샬링(분리)한다.
data = stNiceCardInfoReq.unpack(recvData)

PySide와 Qt designer 개발환경 만들기

Python 2.7.3 기준

1) Python 2.7.3을 설치 ( http://www.python.org/download/ )

2) Python 버전에 맞는 PySide를 설치( http://qt-project.org/wiki/Get-PySide )
    -> Qt designer는 PySide설치시 포함( Python설치경로\Lib\site-packages\PySide )

3) setuptools 설치( http://peak.telecommunity.com/DevCenter/setuptools )
    -> "PySide-uic"( Qt designer 포맷인 "XX.ui"를 Python포맷으로 코드생성을 하는 툴 )
         사용을 가능하게 한다

3번에서 한참 삽질을 하다 구글신님이 답을 주셨도다
혹시나 잊어버릴지 몰라 메모
홈