我正在编写一个Python脚本,它将不断地抓取数据,但它将花费相当长的时间。有没有安全的方法来阻止长时间运行的python脚本?循环将运行超过10分钟,我需要一个方法来阻止它,如果我想,在它已经运行之后。
如果我从cron作业执行它,那么我假设它会一直运行到它完成为止,那么我该如何阻止它呢?
另外,如果我在浏览器上运行它,只需调用该文件。我认为阻止页面加载会让它停止,对吗?
,这是一个场景:
我有一个python脚本,它从页面中收集信息并将其放入队列中。然后,我希望有另一个python脚本,它位于一个无限循环中,它只检查队列中的新项。假设我希望无限循环在早上8点开始,晚上8点结束。我怎样才能做到这一点?
发布于 2012-08-10 09:18:02
让我给你一个替代方案。看起来你想要实时更新某种信息。可以使用pub/sub接口(发布/订阅)。因为您正在使用python,所以有很多可能性。
其中之一是使用Redis发布/子功能:http://redis.io/topics/pubsub/ -下面是对应的python模块:红皮
-更新-
示例
import sys
import threading
import cmd
def monitor():
r = redis.Redis(YOURHOST, YOURPORT, YOURPASSWORD, db=0)
channel = sys.argv[1]
p = r.pubsub()
p.subscribe(channel)
print 'monitoring channel', channel
for m in p.listen():
print m['data']
class my_cmd(cmd.Cmd):
"""Simple command processor example."""
def do_start(self, line):
my_thread.start()
def do_EOF(self, line):
return True
if __name__ == '__main__':
if len(sys.argv) == 1:
print "missing argument! please provide the channel name."
else:
my_thread = threading.Thread(target=monitor)
my_thread.setDaemon(True)
my_cmd().cmdloop()-更新2-
此外,请参阅本教程:
http://blog.abourget.net/2011/3/31/new-and-hot-part-6-redis-publish-and-subscribe/
发布于 2012-08-10 09:13:16
我想解决这个问题的一种方法是为一个循环运行一个脚本,这将是:
现在,您可以在上午8点之间的每分钟运行这个脚本。晚上8点。唯一的缺点是新的项目可能会有一段时间被处理。
发布于 2012-08-10 10:40:35
我认为保持浏览器页面并不一定会停止python脚本,我建议您在父进程的控制下使用叉启动脚本:
输入os,时间,信号
def child():
print 'A new child ', os.getpid( )
time.sleep(5)
os._exit(0)
def parent():
while True:
newpid = os.fork()
if newpid == 0:
child()
else:
pids = (os.getpid(), newpid)
print "parent: %d, child: %d" % pids
print "start counting time for child process...!"
time1 = time.clock()
while True:
#time.sleep(1)
time2 = time.clock()
# Check if the execution time for child process exceeds 10 minutes...
if time2-time1 >= 2 :
os.kill(int(newpid), signal.SIGKILL)
break
if raw_input( ) == 'q': break
parent()https://stackoverflow.com/questions/11898451
复制相似问题