python线程暂停
Ⅰ 求助python多线程,执行到100多个停止了
python 线程 暂停, 恢复, 退出
我们都知道python中可以是threading模块实现多线程, 但是模块并没有提供暂停, 恢复和停止线程的方法, 一旦线程对象调用start方法后, 只能等到对应的方法函数运行完毕. 也就是说一旦start后, 线程就属于失控状态. 不过, 我们可以自己实现这些. 一般的方法就是循环地判断一个标志位, 一旦标志位到达到预定的值, 就退出循环. 这样就能做到退出线程了. 但暂停和恢复线程就有点难了, 我一直也不清除有什么好的方法, 直到我看到threading中Event对象的wait方法的描述时.
wait([timeout])
Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs.
阻塞, 直到内部的标志位为True时. 如果在内部的标志位在进入时为True时, 立即返回. 否则, 阻塞直到其他线程调用set()方法将标准位设为True, 或者到达了可选的timeout时间.
When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof).
This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out.
当给定了timeout参数且不为None, 它应该是一个浮点数,以秒为单位指定操作的超时(或是分数)。
此方法在退出时返回内部标志,因此除非给定了超时且操作超时,否则它将始终返回True。
Changed in version 2.7: Previously, the method always returned None.
2.7版本以前, 这个方法总会返回None.
<br>
利用wait的阻塞机制, 就能够实现暂停和恢复了, 再配合循环判断标识位, 就能实现退出了, 下面是代码示例:
#!/usr/bin/env python
# coding: utf-8
import threading
import time
class Job(threading.Thread):
def __init__(self, *args, **kwargs):
super(Job, self).__init__(*args, **kwargs)
self.__flag = threading.Event() # 用于暂停线程的标识
self.__flag.set() # 设置为True
self.__running = threading.Event() # 用于停止线程的标识
self.__running.set() # 将running设置为True
def run(self):
while self.__running.isSet():
self.__flag.wait() # 为True时立即返回, 为False时阻塞直到内部的标识位为True后返回
print time.time()
time.sleep(1)
def pause(self):
self.__flag.clear() # 设置为False, 让线程阻塞
def resume(self):
self.__flag.set() # 设置为True, 让线程停止阻塞
def stop(self):
self.__flag.set() # 将线程从暂停状态恢复, 如何已经暂停的话
self.__running.clear() # 设置为False
下面是测试代码:
a = Job()
a.start()
time.sleep(3)
a.pause()
time.sleep(3)
a.resume()
time.sleep(3)
a.pause()
time.sleep(2)
a.stop()
<br>
测试的结果:
这完成了暂停, 恢复和停止的功能. 但是这里有一个缺点: 无论是暂停还是停止, 都不是瞬时的, 必须等待run函数内部的运行到达标志位判断时才有效. 也就是说操作会滞后一次.
但是这有时也不一定是坏事. 如果run函数中涉及了文件操作或数据库操作等, 完整地运行一次后再退出, 反而能够执行剩余的资源释放操作的代码(例如各种close). 不会出现程序的文件操作符超出上限, 数据库连接未释放等尴尬的情况.
Ⅱ python怎么让进程暂停
加个阻塞,条件ok后在继续,可以用input()、多线程、多进程、协程等都可以。
Ⅲ python 暂停,继续线程
Python3, 使用 Thread 对象的 Lock 和 Rlock 可以实现简单的线程同步,这两个对象都有 acquire 方法和 release 方法,对于那些需要每次只允许一个线程操作的数据,可以将其操作放到 acquire 和 release 方法之间。
Ⅳ Python 如何强制中止线程
Python用sleep停止一个线程的运行,而不影响主线程的运行,案例代码如下:
from threading import *import time class MyThread(Thread): def run (self): self.ifdo = True; while self.ifdo: print 'I am running...' time.sleep(2) def stop (self): print 'I am stopping it...' self.ifdo = False; tr = MyThread()tr.setDaemon(True)tr.start()print 'I will stop it...'time.sleep(5)tr.stop()tr.join()
Ⅳ python 暂停几秒执行下一步、
在代码开头引入time模块:import time
在需要延时的地方加入语句:time.sleep(1)
(括号中的1意为停顿1秒,想停顿时间更长可以换数字)
举例:
import time
print '11'
time.sleep(10)
print '22'
先打印11,等待10秒后,打印22。
(5)python线程暂停扩展阅读:
文件执行
1、用 notepad++ 或 Sublime Text,甚至 写字本创建一个文件。
2、比如:print('Hello world!')
3、保存为 helloworld.py,一定要选或写后缀名 .py 。
4、进入cmd命令行,切换(cd)到保存文件的目录,执行 python helloworld.py,文件名前的python表示调用python解释器执行文件。
Ⅵ Python中如何在一段时间后停止程序
用到threading的Timer,也类似单片机那样子,在中断程序中再重置定时器,设置中断,python实例代码如下:
import threading
import time
def change_user():
print('这是中断,切换账号')
t = threading.Timer(3, change_user)
t.start()
#每过3秒切换一次账号
t = threading.Timer(3, change_user)
t.start()
while True:
print('我在爬数据')
time.sleep(1)
(6)python线程暂停扩展阅读
有时当一个条件成立的情况下,需要终止程序,可以使用sys.exit()退出程序。sys.exit()会引发一个异常:
1、如果这个异常没有被捕获,那么python编译器将会退出,后面的程序将不会执行。
2、如果这个异常被捕获(try...except...finally),捕获这个异常可以做一些额外的清理工作,后面的程序还会继续执行。
注:0为正常退出,其他数值(1-127)为不正常,可抛异常事件供捕获。另一种终止程序的方法os._exit()
一般情况下使用sys.exit()即可,一般在fork出来的子进程中使用os._exit()
采用sys.exit(0)正常终止程序,程序终止后shell运行不受影响。
采用os._exit(0)关闭整个shell,调用sys._exit(0)后整个shell都重启了(RESTART Shell)。
Ⅶ python里如何终止线程 比如线程里调用os.system('adb logcat')这个是不会停止的
如果直接终止线程不清楚,要不曲线下,新开启一个进程,再得到这个进程id,然后干掉这个进程
import
multiprocessing
def
NewProcess():
global
id
id=os.getpid()
os.system('adb
logcat')
NP=multiporcess.Process(target=one
function,args=())
NP.start()
os.kill(id,9)
Ⅷ Python中怎么在终止一个线程的同时终止另外一个线程
设置一个全局变量,初值为False
设置键盘监听事件,当监测到特定按键时,将全局变量的值修改为True
在每个子线程中,循环检测全局变量的值,当检测到值为True时退出线程函数。
Ⅸ python 在线程函数中如何实现线程的暂停、恢复和终止
我们都知道python中可以是threading模块实现多线程, 但是模块并没有提供暂停, 恢复和停止线程的方法, 一旦线程对象调用start方法后, 只能等到对应的方法函数运行完毕. 也就是说一旦start后, 线程就属于失控状态. 不过, 我们可以自己实现这些. 一般的方法就是循环地判断一个标志位, 一旦标志位到达到预定的值, 就退出循环. 这样就能做到退出线程了. 但暂停和恢复线程就有点难了, 我一直也不清除有什么好的方法
Ⅹ Python里如何终止一个线程
Python用sleep停止一个线程的运行,而不影响主线程的运行,案例代码如下:
fromthreadingimport*
importtime
classMyThread(Thread):
defrun(self):
self.ifdo=True;
whileself.ifdo:
print'Iamrunning...'
time.sleep(2)
defstop(self):
print'Iamstoppingit...'
self.ifdo=False;
tr=MyThread()
tr.setDaemon(True)
tr.start()
print'Iwillstopit...'
time.sleep(5)
tr.stop()
tr.join()