#_____________IO
<pre name="code" class="python">from io import StringIO
f = StringIO()#BytesIO f.write('中文'.encode('utf-8'))
f.write("hello")
f.write(",world")
print(f.getvalue())
import pickle
d = dict(key1='liu',key2=23)
f = open('dump.txt','wb')
pickle.dump(d,f)
f.close
f = open('dump.txt','rb')
d = pickle.load(f)
print(d)
import json
j = json.dumps(d)
print(j)
</pre><p></p><p>#Process</p><pre code_snippet_id="1790848" snippet_file_name="blog_20160728_5_6131348" name="code" class="python">from multiprocessing import Pool
import os, time, random
def long_time_task(name):
print('Run task %s (%s)...' % (name, os.getpid()))
start = time.time()
time.sleep(random.random() * 3)
end = time.time()
print('Task %s runs %0.2f seconds.' % (name, (end - start)))
if __name__=='__main__':
print('Parent process %s.' % os.getpid())
p = Pool()
for i in range(5):
p.apply_async(long_time_task, args=(i,))
print('Waiting for all subprocesses done...')
p.close() #不能添加新的process了
p.join()
print('All subprocesses done.')
#Lock
import threading,time
apple = 0
lock = threading.Lock()
def eating():
global apple
while True:
lock.acquire()
try:
apple = apple - 1
print("the %s eating one,the apple_num is %d" %(threading.current_thread().name, apple) )
finally:
time.sleep(1)
lock.release()
def producing():
global apple
while True:
lock.acquire()
try:
apple = apple + 1
print("the %s producing one,the apple_num is %d" %(threading.current_thread().name, apple))
finally:
time.sleep(1)
lock.release()
t1 = threading.Thread(target = eating ,name = "吃的人")
t2 = threading.Thread(target = producing , name = "做的人")
t1.start()
t2.start()
t1.join()
t2.join()