Python Library实际应用操作步骤详解

开发 后端
如果你也在Python Library的实际应用操作步骤中有一些疑惑时,你可以浏览我们的文章对Python Library的相关知识有一个更深的了解。

在Python Library的实际操作过程中,如果你对Python Library的实际操作步骤不是很了解的话,你可以通过我们的文章,对其有一个更好的了解,希望你通过我们的文章,会对你在此方面额知识有所提高。
Python 2.6.4 Standard Library 提供了 thread 和 threading 两个 Module,其中 thread 明确标明了如下文字。

The thread module has been renamed to _thread in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0; however, you should consider using the high-level threading module instead.

1. Thread

我们可以选择继承 Thread 来实现自己的线程类,或者直接像 C# Thread 那样传个函数进去。

 

  1. from threading import *  
  2. def t(a, b):  
  3. print currentThread().name, a, b  
  4. Thread(ttarget = t, args = (1, 2)).start()  

 

输出:

  1. $ ./main.py  
  2. Thread-1 1 2  

 

Python Library要实现自己的线程类,可以重写 __init__() 和 run() 就行了。不过一旦我们定义了 run(),我们传进去的 target 就不会自动执行了。

 

  1. class MyThread(Thread):  
  2. def __init__(self, name, x):  
  3. Thread.__init__(self, namename=name)  
  4. self.x = x  
  5. def run(self):  
  6. print currentThread().name, self.x  
  7. MyThread("My", 1234).start()   

 

输出:

  1. $ ./main.py  
  2. My 1234   

 

Thread 有个重要的属性 daemon,和 .NET Thread.IsBackground 是一个意思,一旦设置为 Daemon Thread,就表示是个 "后台线程"。

 

  1. def test():  
  2. for i in range(10):  
  3. print currentThread().name, i  
  4. sleep(1)  
  5. t = Thread(target = test)  
  6. #t.daemon = True 
  7. t.start()  
  8. print "main over!"   

 

输出:

  1. $ ./main.py  

非 Daemon 效果,Python Library进程等待所有前台线程退出。

 

  1. Thread-1 0  
  2. main over!  
  3. Thread-1 1  
  4. Thread-1 2  
  5. Thread-1 3  
  6. Thread-1 4  
  7. Thread-1 5  
  8. Thread-1 6  
  9. Thread-1 7  
  10. Thread-1 8  
  11. Thread-1 9  
  12. $ ./main.py # IsDaemon  

进程不等待后台线程。

  1. Thread-1 0  
  2. main over! 

以上文章就是对Python Library的实际应用操作步骤的介绍。

【编辑推荐】

  1. 用Python小程序建立命令行的实际应用方案
  2. PythonS60手机中搭建手机运行平台的五个步骤
  3. Python字符串中的mapping的功能介绍
  4. Python web框架在实际操作过程中的缺点
  5. Python二维数组在创建过程中步骤详解
责任编辑:佚名 来源: 博客园
相关推荐

2010-03-23 14:54:27

Python目录文件

2010-03-09 19:07:01

Python语法

2010-03-22 19:11:55

Python连接

2010-03-17 13:14:00

Python Libr

2010-03-17 10:01:12

Python安装

2009-08-25 17:02:20

C#串口操作

2010-03-17 12:53:43

Python Libr

2010-12-07 09:20:44

MySQL limit

2010-03-17 16:27:39

Python矩阵转置

2010-03-05 13:48:24

Python for

2010-03-24 17:03:57

Python源码分析

2010-06-01 15:54:46

MySQL-pytho

2010-03-12 15:29:19

Pythonexe

2010-03-17 12:37:51

Python定时器

2010-03-24 13:17:35

Python嵌入

2010-03-15 16:54:11

Python字典

2010-04-20 11:06:33

Oracle索引

2010-03-22 10:11:28

Python Libr

2010-03-17 14:18:27

Python open

2010-03-25 18:37:28

Python技巧
点赞
收藏

51CTO技术栈公众号