我想知道如何使用 CTRL+C 或类似的方法在控制台中停止我的程序。问题是我的程序中有两个线程。线程 1 爬取网络并提取一些数据,线程 2 以用户可读的格式显示这些数据。两个部分共享相同的数据库。我像这样运行它们:
from threading import Thread
import ResultsPresenter
def runSpider():
Thread(target=initSpider).start()
Thread(target=ResultsPresenter.runPresenter).start()
if __name__ == "__main__":
runSpider()
我怎样才能做到这一点?
好的,所以我创建了自己的线程类:
import threading
class MyThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(MyThread, self).__init__()
self._stop = threading.Event()
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
好的,所以我将在这里发布 resultPresenter 和爬虫的片段。这是 resultPresenter 的代码:
# configuration
DEBUG = False
DATABASE = database.__path__[0] + '/database.db'
app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('CRAWLER_SETTINGS', silent=True)
def runPresenter():
url = "http://127.0.0.1:5000"
webbrowser.open_new(url)
app.run()
这里还有两个方法我省略了 - 其中一个连接到数据库,第二个方法加载 html 模板以显示结果。我重复此操作,直到满足条件或用户停止程序(我正在尝试实施)。还有另外两种方法——一种是从命令行获取初始链接,另一种是经过验证的参数——如果参数无效,我将不会运行 crawl() 方法。
这是爬虫的简短版本:
def crawl(initialLink, maxDepth):
#here I am setting initial values, lists etc
while not(depth >= maxDepth or len(pagesToCrawl) <= 0):
#this is the main loop that stops when certain depth is
#reached or there is nothing to crawl
#Here I am popping urls from url queue, parse them and
#insert interesting data into the database
parser.close()
sock.close()
dataManager.closeConnection()
这是在线程中启动这些模块的初始化文件:
import ResultsPresenter, MyThread, time, threading
def runSpider():
MyThread.MyThread(target=initSpider).start()
MyThread.MyThread(target=ResultsPresenter.runPresenter).start()
def initSpider():
import Crawler
import database.__init__
import schemas.__init__
import static.__init__
import templates.__init__
link, maxDepth = Crawler.getInitialLink()
if link:
Crawler.crawl(link, maxDepth)
killall = False
if __name__ == "__main__":
global killall
runSpider()
while True:
try:
time.sleep(1)
except:
for thread in threading.enumerate():
thread.stop()
killall = True
raise