'Study/Python'에 해당되는 글 3건

Study/Python

펌웨어 바이너리 파일 등 hexadecimal 값을 가독성이 좋은 형태로 변환해야 하는 경우가 있다.

 

예를들면

0x00 0x11 0x22 ...  => 001122 의 형태로

 

간단하게

import binascii

binascii.hexlify(), binascii.unhexlify()를 활용하면 된다.

 

 

의 결과 값은 아래와 같다.

 

 

character '1'의 hex 값은 0x31이다.

http://www.asciitable.com/

 

Ascii Table - ASCII character codes and html, octal, hex and decimal chart conversion

ASCII Table and Description ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII code is the numerical representation of a character such as 'a' or '@' or an action of some sort. ASCII was

www.asciitable.com

 

 

만약 특정 바이너리 파일을 모두 컨버팅 하기 위해서는 아래와 같이 하면 된다.

결과.

 

'Study > Python' 카테고리의 다른 글

python 함수 주기적으로 실행하기  (0) 2017.01.25
python Queue 사용방법  (0) 2017.01.25
Study/Python

python에서 특정 함수를 일정 주기마다 실행하고 싶으면? threading.Timer를 사용해보자


기본 사용방법은 아래와 같다.


import threading

class AsyncTask:
def __init__(self):
pass

def TaskA(self):
print 'Process A'
threading.Timer(1,self.TaskA).start()

def TaskB(self):
print 'Process B'
threading.Timer(3, self.TaskB).start()

def main():
print 'Async Function'
at = AsyncTask()
at.TaskA()
at.TaskB()

if __name__ == '__main__':
main()

수행 결과, TaskA는 1초마다, TaskB는 3초마다 수행되고 있다.


Async Function

Process A

Process B

Process A

Process A

Process B

Process A

Process A

Process A

Process B


핵심은 아래 함수이다.

threading.Timer(1,self.TaskA).start()

함수의 의미는 1초 후에 TaskA를 start하라는 의미이다.

TaskA 함수안에서 threading.Timer를 사용한다면 TaskA는 정해진 시간마다 주기적으로 수행되는 함수가 될 것이다.



가장 중요한 점은, TaskA를 최초의 한번은 수행햐주어야 한다는 점이다.

def main():
print 'Async Function'
at = AsyncTask()
at.TaskA()
at.TaskB()




'Study > Python' 카테고리의 다른 글

python hex값을 hex string으로 변환하기, hexlify(), unhexlify()  (0) 2019.05.07
python Queue 사용방법  (0) 2017.01.25
Study/Python

Python에서 Queue의 기본적인 사용법은 아래와 같다.


import Queue

q = Queue.Queue()

items=list()

items.append('item1')
items.append('item2')
items.append('item3')
items.append('item4')
items.append('item5')

print 'start queue'

for i in items:
q.put(i)

while q.qsize():
print q.get()

print 'end queue'


put() 함수를 사용해서 q(queue)에  item1~item5 까지 put을 수행한다. get() 함수를 사용해서 q를 비운다.

위 코드를 수행하면 아래와 같은 결과가 나온다


item1

item2

item3

item4

item5

end queue


위 동작은 item1~item5 까지를 한번에 모두 Queue에 넣고 한꺼번에 get을 수행하기 때문에 전혀 문제가 없다.


그런데 여러 Thread 상에서 비동기적으로 Queue에 put과 get을 수행해야하는 상황이라면 문제가 생긴다.


put()과 get() 함수가 기본적으로 blocking 함수이기 때문이다.


흔히 발생할 수 있는 상황은, Queue에 데이터가 없는 상황에서 get() 함수를 수행한다면 데이터가 put() 될때까지 blocking 되기 때문에 해당 Thread에서 다른 동작을 수행할 수가 없다.


해결 방법은 get()과 put()을 non-blocking 함수로 바꿔야 하는데, 방법은 아래와 같다.


import Queue

q = Queue.Queue()

items=list()

items.append('item1')
items.append('item2')
items.append('item3')
items.append('item4')
items.append('item5')

print 'start queue'

for i in items:
q.put_nowait(i)

while q.qsize():
print q.get_nowait()

print 'end queue'



1
블로그 이미지

IoT 개발자 블로그이고 싶다.

1byte