-
python 코딩Programming 2017. 1. 31. 15:00
python http 코딩
1. request보내기
import requests
r = requests.get('https://api.github.com/events')
r = requests.post('http://httpbin.org/post', data = {'key':'value'})
2. cookie값 추가
import requests
req_cookies = dict(style=cookie)
r = requests.get('https://api.github.com/events', cookies = request_cookies)
3. 웹으로부터 파일 받아오기
import urllib
testfile = urllib.URLopener()
testfile.retrieve("http://randomsite.com/file.gz", "file.gz")
This downloads a file from a website and names it file.gz. This is one of my favorite solutions, from Downloading a picture via urllib and python.
This example uses the urllib library, and it will directly retrieve the file form a source.
http://stackoverflow.com/questions/19602931/basic-http-file-downloading-and-saving-to-disk-in-python
4. 웹으로 부터 이미지 얻어오기
def download(station1_axi, station2_axi, filename):
url = 'http://openapi.naver.com/map/getStaticMap?version=1.0&crs=EPSG:4326&format=png'
url+= '¢er=127.3811454,36.3574425&level=9&w=640&h=640&maptype=default'
url+= '&markers='+station1_axi+'&markers='+station2_axi+'&key=4b524c75d25cf78226578ec4604721b8'
url+= '&uri=localhost:8080'
file_path = "%s%s" % ("C:\\Users\\h0ng\\Documents\\mapimg\\",filename)
download_img = file(file_path, "wb")
img_on_web = urllib.urlopen(url)
while True:
buf = img_on_web.read(10000000)
if len(buf) == 0:
break
download_img.write(buf)
download_img.close()
img_on_web.close()
출처 : http://marobiana.tistory.com/103
string관련
'string find
temp = "abcdefg"
print temp
n = temp.find('c')
print n
문자열 split
>>> line = "BGP4MP|1354132819|W|67.17.82.114|3549|95.29.252.0/24"
>>> parts = line.strip().split('|')
>>> parts
['BGP4MP', '1354132819', 'W', '67.17.82.114', '3549', '95.29.252.0/24']
>>> format_type, timestamp, message_type = parts[:3]
>>> format_type
'BGP4MP'
>>> timestamp
'1354132819'
find과 없으면, -1 있으면, array에서 해당 문자열의 첫 바이트 위치 반환
str.join()
http://stackoverflow.com/questions/12453580/concatenate-item-in-list-to-strings
casting
num=hex(42)
int(num,16)
int는 16진수num을 int로 바꾸어 준다.
시스템 관련
dll의 함수주소 얻기
h_kernel32 = kernel32.GetModuleHandleA("kernel32.dll")
h_ExitProcess = kernel32.GetProcAddress(h_kernel32, "ExitProcess")
socket timeout
1초뒤에 timeout exception발생시킨다.
s.settimeout(1)
while 1:
try:
print s.recv(512)
except timeout:
break
'
thread관련
threads = []
for i in range(100):
threads.append(RestrictedArea())
for th in threads:
th.start() # 쓰레드 시작
for th in threads:
th.join() # 종료대기
print 'Finish All Threading '
thread, process종료하기
프로세스의 종료
프로세스는 다음과 같이 네 가지 방법으로 종료될 수 있다.
주(main) 쓰레드의 진입점 함수(main)가 반환되었다. (Best)
프로세스 내의 어떤 쓰레드가 ExitProcess 함수를 호출하였다 (Not recommended)
다른 프로세스의 쓰레드가 TerminateProcess 함수를 호출하였다 (Not recommended)
프로세스 내의 모든 쓰레드가 종료되었다.
http://sweeper.egloos.com/m/2979306
- TerminateProcess()
1. 자기 자신이 아닌 다른 프로세스를 종료시킬 수 있다.
2. 정리 작업을 하지 않기 때문에 되도록 금지되는 함수
http://pkss.tistory.com/entry/ExitProcess-TerminateProcess-PostQuitMessage-%EC%B0%A8%EC%9D%B4%EC%A0%90
-CreateRemoteThread를 사용한 process종료
#DO NOT USE terminate_process
thread_id = c_ulong(0)
exitcode = c_uint(1)
kernel32.CreateRemoteThread(h_process, None, 0, h_ExitProcess, byref(exitcode),0, byref(thread_id))
kernel32.TerminateProcess(self.pid,None)
self.pid = None
http://www.devpia.com/MAEUL/Contents/Detail.aspx?BoardID=51&MAEULNO=20&no=6645
좀 느림..
pydbg일 경우는 self.dbg.terminate_process() 써서 process죽임.
세마포어
- semaphore
import threading
sem = threading.Semaphore(3)
critical section에 제한된 수의 쓰레드만 진입가능하게 설정
- acquire()
semaphore 값 1감소 / semaphore값이 0 이면 쓰레드는 세미포 대기큐에 들어가 block 상태가 된다.
- release()
호출되면, 먼저 세마포 대기큐를 검사해서 하나를 풀어준다, 대기큐에 없으면 변수값 1증가
파일 관련
파일 open with 'a' option
f = open("file.txt",'a')
'a'옵션은 추가모드.
file.txt 원래 가지고 있던 내용 바로 다음부터 결과값을 write할 수 있다.
포인터
c_type value = byref(pointer)
pointer = POINTER(c_type value)
>>> s = "Hello, World"
>>> c_s = c_char_p(s)
>>> print c_s
c_char_p('Hello, World')
>>> c_s.value = "Hi, there"
>>> print c_s
c_char_p('Hi, there')
>>> print s # first string is unchanged
Hello, World
from ctypes import *
Foo = windll.mydll.Foo
Foo.argtypes = [ POINTER( POINTER( c_ubyte ) ), POINTER( c_int ) ]
mem = POINTER( c_ubyte )()
size = c_int( 0 )
Foo( byref( mem ), byref( size ) ]
print size, mem[ 0 ], mem[ 1 ], mem[ 2 ], mem[ 3 ]
바이트 처리
>>print fd.read(1)
1바이트 읽은게 ascii로 프린트 된다.
>>print pack('b')
>>0x42
pack함수는 integer를 binary로 바꿔준다.
>>print unpack('/0x50/x00')
>>5
unpack함수는 binary를 integer로 바꿔준다.
bbtracer시 reader.py 확인할 것.
datetime 관련
sdate = "20130601001149"
def parsing_datetime(sdate):
return_time = datetime(int(sdate[:4]), int(sdate[4:6]), int(sdate[6:8]),int(sdate[8:10]), int(sdate[10:12]), int(sdate[12:14]))
return return_time
>>> d = datetime.datetime(2004,12,12,12,12,12)
>>> d
datetime.datetime(2004, 12, 12, 12, 12, 12)
>>> d.strftime(fmt)
'2004-12-12 12:12:12'
아래와 같이 pandas module을 이용하면 datetime끼리 +,-연산이 가능하다.
from pandas.tseries.offsets import Hour, Minute
iterator_time < rent_time + Minute(30)
'Programming' 카테고리의 다른 글
Visual studio 환경 세팅 (0) 2017.06.24 fsharp compiler, interpreter 작업환경 (0) 2017.04.21 C++ 문자열 및 파일 (0) 2016.06.07 sourceforces 158B - 10 (0) 2016.05.19 making fuzzer w/ eclipse pydev (0) 2016.04.09