刚开始我在做爬虫,爬虫程序用python程序调用,但有时候爬虫程序会死掉,挂了,所以程序会一直停留在那儿,该怎么办呢?我想可以建立一个坚守程序,让os.system()调用爬虫程序能在一定时间内未执行完时,强制杀死,并重新开始,但根据结构化程序,顺序执行没办法做到这一点,我知道肯定需要线程机制实现,网上找到了subprocess这个模块,它会创建一个子进程,还有一个类Popen(),还是挺好用的。
#coding=utf-8
import subprocess
import time
#child=subprocess.Popen(['ping','-t','5','www.google.com'])
pan=None
while pan!=0:
child=subprocess.Popen('casperjs C:\\Users\\MINUS\\Desktop\\一次登录.js') #建立子进程
#print child.poll()
#print child.wait() #这里不适合wait函数,因为这个函数会让子进程进行完
#print child.returncode
time.sleep(10) #给10s的时间去执行子进程,时间内执行不了就重启子进程
print 'parent'
#print child.returncode #获取进程的返回值
print child.poll() #进程结束返回0 ,否则为Nonoe
pan=child.poll()
if pan!=0: #进程没结束
child.kill() #杀死这个进程 进入循环重新执行 child.terminate()这个也是可以的
关于subprocess模块的各个函数讲解我这里就不讲了,可以参考
http://blog.youkuaiyun.com/hansel/article/details/8944785 优快云文档
https://docs.python.org/2/library/subprocess.html#subprocess.Popen.stderr 官方文档
上面的讲解过程差不多,应该能了解了
返回结果是这样的:
I've wait 2 seconds
start url:http://weibo.com/signup/signup.php?inviteCode=3105241737
parent
None
parent
None
I've wait 2 seconds
start url:http://weibo.com/signup/signup.php?inviteCode=3105241737
parent
None
parent
None
parent
None
parent
None
I've wait 2 seconds
start url:http://weibo.com/signup/signup.php?inviteCode=3105241737
parent
None
I've wait 2 seconds
start url:http://weibo.com/signup/signup.php?inviteCode=3105241737