如何在python上覆盖树莓派3的线程?
的问题是,我找不到任何 答案与谷歌搜索方面相对只有简单:如何在python上覆盖树莓派3的线程?
- 如何终止线程在python
- 如何同时使用线程等 键盘输入回路结束
所以程序的格式是这样的:
import everything necessary
def readingsomething():
DOING SOME WORK in a infinite while loop and sleep for 1 sec
def readingsomeotherthing():
DOING SOME WORK in a infinite while loop and sleep for 2 sec
thread1 = thread.thread(target = readingsomething)
thread2 = thread.thread(target = readingsomeotherthing)
try:
thread1.start()
thread2.start()
thread1.join()
thread2.join()
except KeyboardInterrupt:
save a file and sys.exit()
所以,当我运行方案E verything是除非我 按CTRL 顺利 + Ç它不会终止每一个KeyboardInterrupt
,因为我失去了收集到的数据,因为我无法拯救他们。
任何建议和帮助将不胜感激。
这是相当不清楚你想要做什么。 你正在谈论循环,但我没有看到你的代码。
另外,就像这样写,你将首先等待thread1停止,然后等待thread2停止,确保它是你想要的。
把超时内这些“加入”要求,否则它可以防止异常的听力:
thread1.join()
成为
thread1.join(10)
你可能要考虑一下导致你的代码的变化。
谢谢你的建议,我会尝试它。 循环在定义的函数中。 –
工作的Python 3例子:
from threading import Thread, Event
import time
def readingsomething(stop):
while not stop.isSet():
print('readingsomething() running')
time.sleep(1)
def readingsomeotherthing(stop):
while not stop.isSet():
print('readingsomeotherthing() running')
time.sleep(2)
if __name__ == '__main__':
stop = Event()
thread1 = Thread(target=readingsomething, args=(stop,))
thread2 = Thread(target=readingsomeotherthing, args=(stop,))
thread1.start()
thread2.start()
try:
thread1.join()
thread2.join()
except KeyboardInterrupt:
print('catched KeyboardInterrupt')
stop.set()
#save the file
print('EXIT __main__')
与Python测试:3.4.2
谢谢你的建议,我会试试这个。 –
由于我使用python3, 键=输入('按ctrl + c终止')变成 键= eval(输入('按ctl + c终止'),但我一直得到无效的语法错误的C,我试图找到原因 –
@PradeepBV:更新我的答案与工作示例 – stovfl
嗨,欢迎堆栈溢出。发布时请务必使用[正确的格式](https://stackoverflow.com/editing-help#code),以便帮助您的人更容易阅读代码。 –
善意地缩进你的代码 - 当你执行它时。问题到底是什么? –
该代码编译没有错误,并执行,但它应该终止只按下Ctrl + C但它不会停止并继续执行我认为这是一个问题,因为睡眠命令在函数 –