-
Notifications
You must be signed in to change notification settings - Fork 419
Expand file tree
/
Copy pathprocess.html
More file actions
596 lines (449 loc) · 16.9 KB
/
Copy pathprocess.html
File metadata and controls
596 lines (449 loc) · 16.9 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>2.3. 进程与线程</title><link rel="stylesheet" type="text/css" href="../docbook.css" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><meta name="keywords" content="php,pear,pecl,phar, python, , " /><link rel="home" href="../index.html" title="Netkiller Python 手札" /><link rel="up" href="index.html" title="第 2 章 Library" /><link rel="prev" href="random.html" title="2.2. 随机数" /><link rel="next" href="python.log.html" title="2.4. 日志" /></head><body><a xmlns="" href="//www.netkiller.cn/">Home</a> | <a xmlns="" href="//netkiller.github.io/">简体中文</a> | <a xmlns="" href="http://netkiller.sourceforge.net/">繁体中文</a> | <a xmlns="" href="/journal/index.html">杂文</a>
| <a xmlns="" href="https://github.com/netkiller">Github</a> | <a xmlns="" href="https://zhuanlan.zhihu.com/netkiller">知乎专栏</a> | <a xmlns="" href="https://www.facebook.com/bg7nyt">Facebook</a> | <a xmlns="" href="http://cn.linkedin.com/in/netkiller/">Linkedin</a> | <a xmlns="" href="https://www.youtube.com/user/bg7nyt/videos">Youtube</a> | <a xmlns="" href="//www.netkiller.cn/home/donations.html">打赏(Donations)</a> | <a xmlns="" href="//www.netkiller.cn/home/about.html">About</a><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">2.3. 进程与线程</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="random.html">上一页</a> </td><th width="60%" align="center">第 2 章 Library</th><td width="20%" align="right"> <a accesskey="n" href="python.log.html">下一页</a></td></tr></table><hr /></div><table xmlns=""><tr><td><iframe src="//ghbtns.com/github-btn.html?user=netkiller&repo=netkiller.github.io&type=watch&count=true&size=large" height="30" width="170" frameborder="0" scrolling="0" style="width:170px; height: 30px;" allowTransparency="true"></iframe></td><td><iframe src="//ghbtns.com/github-btn.html?user=netkiller&repo=netkiller.github.io&type=fork&count=true&size=large" height="30" width="170" frameborder="0" scrolling="0" style="width:170px; height: 30px;" allowTransparency="true"></iframe></td><td><iframe src="//ghbtns.com/github-btn.html?user=netkiller&type=follow&count=true&size=large" height="30" width="240" frameborder="0" scrolling="0" style="width:240px; height: 30px;" allowTransparency="true"></iframe></td><td></td><td><a href="https://zhuanlan.zhihu.com/netkiller"><img src="/images/logo/zhihu-card-default.svg" height="25" /></a></td><td valign="middle"><a href="https://zhuanlan.zhihu.com/netkiller">知乎专栏</a></td><td></td><td></td><td></td><td></td></tr></table><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="process"></a>2.3. 进程与线程</h2></div></div></div>
<div class="section"><div class="titlepage"><div><div><h3 class="title"><a id="subprocess"></a>2.3.1. subprocess</h3></div></div></div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id935"></a>2.3.1.1. check_output</h4></div></div></div>
<pre class="programlisting">
sp = subprocess.check_output(cmd)
text = sp.decode('UTF8')
print(text)
</pre>
<p>获取IP地址</p>
<pre class="programlisting">
import subprocess
command = "/usr/bin/ip addr show eth0 | grep 'inet ' | awk '{print $2}' | cut -d/ -f1"
screen = subprocess.check_output(command, shell=True)
print(screen.decode().replace("\n", ""))
</pre>
<p>制定运行目录</p>
<pre class="programlisting">
#!/usr/bin/python
# -*-coding:utf-8-*-
import subprocess
output = subprocess.check_output("ls", cwd="/")
print(output.decode())
output = subprocess.check_output("/usr/bin/git pull", cwd="/opt/netkiller", shell=True)
print(output.decode())
</pre>
</div>
</div>
<div class="section"><div class="titlepage"><div><div><h3 class="title"><a id="threading"></a>2.3.2. Python 多线程</h3></div></div></div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="id936"></a>2.3.2.1. threading 高级线程接口</h4></div><div><h5 class="subtitle">threading — Higher-level threading interface</h5></div></div></div>
<p>创建线程</p>
<pre class="programlisting">
from threading import Thread
import time
def fun1():
print("fun1 begin")
time.sleep(2)
print("fun1 end")
def fun2():
print("fun2 begin")
time.sleep(6)
print("fun2 end")
threads = []
threads.append(Thread(target=fun1))
threads.append(Thread(target=fun2))
print(threads)
if __name__ == "__main__":
for t in threads:
print(t)
t.start()
print("Done")
</pre>
<pre class="screen">
import threading
class MyThread(threading.Thread):
def __init__(self, name=None):
threading.Thread.__init__(self)
self.name = name
def run(self):
print self.name
def test():
for i in range(0, 100):
t = MyThread("thread_" + str(i))
t.start()
if __name__=='__main__':
test()
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="threading.lock"></a>2.3.2.2. Lock 线程锁</h4></div></div></div>
<p>这里实现了一个计数器 count 这个全局变量会被多个线程同时操作,使其能够被顺序相加,需要靠线程锁的帮助。</p>
<pre class="programlisting">
#-*- encoding: utf-8 -*-
import threading
import time
class Test(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self._run_num = num
def run(self):
global count, mutex
threadname = threading.currentThread().getName()
for x in range(int(self._run_num)):
mutex.acquire()
count = count + 1
mutex.release()
print (threadname, x, count)
time.sleep(1)
if __name__ == '__main__':
global count, mutex
threads = []
num = 5
count = 0
# 创建锁
mutex = threading.Lock()
# 创建线程对象
for x in range(num):
threads.append(Test(10))
# 启动线程
for t in threads:
t.start()
# 等待子线程结束
for t in threads:
t.join()
</pre>
<pre class="programlisting">
import threading
# 共享变量
count = 0
# 创建锁
lock = threading.Lock()
def add():
global count
for _ in range(100000):
lock.acquire() # 加锁
count += 1
lock.release() # 释放锁
# 两个线程同时修改共享变量
t1 = threading.Thread(target=add)
t2 = threading.Thread(target=add)
t1.start()
t2.start()
t1.join()
t2.join()
print("最终结果:", count) # 正确结果 200000
</pre>
<p>用 with 加锁</p>
<pre class="programlisting">
import threading
# 共享变量
count = 0
# 创建锁
lock = threading.Lock()
def add():
global count
for _ in range(100000):
with lock:
count += 1
# 两个线程同时修改共享变量
t1 = threading.Thread(target=add)
t2 = threading.Thread(target=add)
t1.start()
t2.start()
t1.join()
t2.join()
print("最终结果:", count) # 正确结果 200000
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="threading.queue"></a>2.3.2.3. Queue 队列</h4></div></div></div>
<p>ref:
http://www.ibm.com/developerworks/aix/library/au-threadingpython/
</p>
<pre class="programlisting">
#!/usr/bin/env python
import Queue
import threading
import urllib2
import time
hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com",
"http://ibm.com", "http://apple.com"]
queue = Queue.Queue()
class ThreadUrl(threading.Thread):
"""Threaded Url Grab"""
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
#grabs host from queue
host = self.queue.get()
#grabs urls of hosts and prints first 1024 bytes of page
url = urllib2.urlopen(host)
print url.read(1024)
#signals to queue job is done
self.queue.task_done()
start = time.time()
def main():
#spawn a pool of threads, and pass them queue instance
for i in range(5):
t = ThreadUrl(queue)
t.setDaemon(True)
t.start()
#populate queue with data
for host in hosts:
queue.put(host)
#wait on the queue until everything has been processed
queue.join()
main()
print "Elapsed Time: %s" % (time.time() - start)
</pre>
<pre class="programlisting">
import threading
import queue
# 创建线程通信队列
q = queue.Queue()
# 生产者线程:往队列放数据
def producer():
for i in range(5):
q.put(f"数据{i}")
print(f"生产:数据{i}")
# 消费者线程:从队列取数据
def consumer():
while True:
data = q.get() # 阻塞等待数据
print(f"消费:{data}")
q.task_done() # 标记处理完成
# 创建线程
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer, daemon=True) # 守护线程
# 启动
t1.start()
t2.start()
# 等待生产者结束 + 队列所有数据处理完
t1.join()
q.join()
print("所有通信完成")
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="threading.event"></a>2.3.2.4. 线程事件</h4></div></div></div>
<pre class="programlisting">
import threading
import time
event = threading.Event()
def waiter():
print("等待信号...")
event.wait() # 阻塞等待
print("收到信号!")
def sender():
time.sleep(2)
print("发送信号!")
event.set()
t1 = threading.Thread(target=waiter)
t2 = threading.Thread(target=sender)
t1.start()
t2.start()
</pre>
<pre class="programlisting">
from datetime import datetime
import threading
import time
event = threading.Event()
def waiter():
while(True):
print("等待信号...")
event.wait() # 阻塞等待
print("收到信号!")
event.clear()
print("-"*20, datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "-"*20)
def sender():
while(True):
time.sleep(2)
print("发送信号!")
event.set()
t1 = threading.Thread(target=waiter)
t2 = threading.Thread(target=sender)
t1.start()
t2.start()
</pre>
<pre class="programlisting">
from datetime import datetime
import threading
import time
event = threading.Event()
def waiter():
print("等待信号...")
while(event.wait()): # 阻塞等待
print("收到信号!")
event.clear()
print("-"*20, datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "-"*20)
def sender():
while(True):
time.sleep(2)
print("发送信号!")
event.set()
t1 = threading.Thread(target=waiter)
t2 = threading.Thread(target=sender)
t1.start()
t2.start()
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="threading.Condition"></a>2.3.2.5. 线程通知</h4></div></div></div>
<pre class="programlisting">
import threading
import time
cond = threading.Condition()
products = []
def producer():
with cond:
products.append("商品")
print("生产完成,通知消费者")
cond.notify() # 唤醒消费者
def consumer():
with cond:
cond.wait() # 等待生产
print("消费者拿到:", products[0])
t1 = threading.Thread(target=consumer)
t2 = threading.Thread(target=producer)
t1.start()
t2.start()
</pre>
<pre class="programlisting">
import threading
import time
cond = threading.Condition()
count = 0
def producer():
while True:
with cond:
# while True:
time.sleep(2)
cond.notify()
def consumer():
global count
print("开始计数器")
while True:
with cond:
cond.wait()
count += 1
print(count)
t1 = threading.Thread(target=consumer)
t2 = threading.Thread(target=producer)
t1.start()
t2.start()
</pre>
<pre class="programlisting">
import threading
import time
cond = threading.Condition()
data = None
def consumer():
global data
# 手动加锁(代替 with)
cond.acquire()
print("消费者:等待数据...")
cond.wait() # 自动释放锁 → 阻塞 → 唤醒后自动重新拿锁
print(f"消费者:拿到数据 -> {data}")
# 手动释放锁
cond.release()
def producer():
global data
cond.acquire()
print("生产者:正在生产数据...")
time.sleep(2)
data = "Hello Threading!"
print("生产者:数据生产完成,通知消费者")
cond.notify() # 唤醒,但不释放锁
cond.release() # 这里释放锁,消费者才能真正运行
t1 = threading.Thread(target=consumer)
t2 = threading.Thread(target=producer)
t1.start()
time.sleep(0.1)
t2.start()
t1.join()
t2.join()
</pre>
</div>
</div>
<div class="section"><div class="titlepage"><div><div><h3 class="title"><a id="daemon"></a>2.3.3. 守护进程(Daemon)</h3></div></div></div>
<p>http://www.myelin.co.nz/post/2003/3/13/#200303135</p>
<pre class="programlisting">
#!/usr/bin/env python
import os, sys
print "I'm going to fork now - the child will write something to a pipe, and the parent will read it back"
r, w = os.pipe() # r,w是文件描述符, 不是文件对象
pid = os.fork()
if pid:
# 父进程
os.close(w) # 关闭一个文件描述符
r = os.fdopen(r) # 将r转化为文件对象
print "parent: reading"
txt = r.read()
os.waitpid(pid, 0) # 确保子进程被撤销
else:
# 子进程
os.close(r)
w = os.fdopen(w, 'w')
print "child: writing"
w.write("here's some text from the child")
w.close()
print "child: closing"
sys.exit(0)
print "parent: got it; text =", txt
</pre>
<pre class="programlisting">
import sys, os
if __name__ == "__main__":
# do the UNIX double-fork magic, see Stevens' "Advanced
# Programming in the UNIX Environment" for details (ISBN 0201563177)
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError, e:
print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)
# decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent, print eventual PID before
print "Daemon PID %d" % pid
sys.exit(0)
except OSError, e:
print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)
# start the daemon main loop
</pre>
<p></p>
<pre class="programlisting">
# Redirect standard file descriptors
sys.stdin = open('/dev/null', 'r')
sys.stdout = open('/dev/null', 'w')
sys.stderr = open('/dev/null', 'w')
</pre>
</div>
</div><script xmlns="" type="text/javascript" id="clustrmaps" src="//cdn.clustrmaps.com/map_v2.js?u=r5HG&d=9mi5r_kkDC8uxG8HuY3p4-2qgeeVypAK9vMD-2P6BYM"></script><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="random.html">上一页</a> </td><td width="20%" align="center"><a accesskey="u" href="index.html">上一级</a></td><td width="40%" align="right"> <a accesskey="n" href="python.log.html">下一页</a></td></tr><tr><td width="40%" align="left" valign="top">2.2. 随机数 </td><td width="20%" align="center"><a accesskey="h" href="../index.html">起始页</a></td><td width="40%" align="right" valign="top"> 2.4. 日志</td></tr></table></div><script xmlns="">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-11694057-1', 'auto');
ga('send', 'pageview');
</script><script xmlns="" async="async">
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?93967759a51cda79e49bf4e34d0b0f2c";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script><script xmlns="" async="async">
(function(){
var bp = document.createElement('script');
var curProtocol = window.location.protocol.split(':')[0];
if (curProtocol === 'https') {
bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
}
else {
bp.src = 'http://push.zhanzhang.baidu.com/push.js';
}
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(bp, s);
})();
</script></body></html>