Python爬蟲之用supervisor使scrapy在服務器後臺運行

折騰緣由

以前都是遠程鏈接服務器,而後在命令行運行scrapy crawl spider,一旦關閉遠程鏈接,爬蟲就會中止,很不爽,畢竟能讓一個爬蟲在服務器一直跑纔是每一個小白的夢想= =,因此開始研究如何使程序在後臺運行,剛開始看了scrapyd,感受很差用,又搜了搜,發現了supervisor這個python進程管理程序。python

supervisor簡介

Supervisor是用Python開發的一套通用的進程管理程序,能將一個普通的命令行進程變爲後臺daemon,並監控進程狀態,異常退出時能自動重啓。它是經過fork/exec的方式把這些被管理的進程看成supervisor的子進程來啓動,這樣只要在supervisor的配置文件中,把要管理的進程的可執行文件的路徑寫進去便可。也實現當子進程掛掉的時候,父進程能夠準確獲取子進程掛掉的信息的,能夠選擇是否本身啓動和報警。supervisor還提供了一個功能,能夠爲supervisord或者每一個子進程,設置一個非root的user,這個user就能夠管理它對應的進程。shell

安裝supervisor

個人系統是centos7因此運行如下命令centos

# yum install supervisor

等待安裝完後,進入/ect目錄,主要看以下兩個文件。
etc
supervisord.conf爲主配置文件,能夠打開看一下,不用更改,supervisord.d爲子進程的配置文件夾,存放在這裏的配置文件在程序啓動後會自動讀取該文件夾下的文件,咱們進入這個文件夾,建立一個子進程文件,名爲awesome.ini,內容以下:服務器

[program:awesome]

command     = shell.py
directory   = /python/scrapy
user        = root
startsecs   = 3

redirect_stderr         = true
stdout_logfile_maxbytes = 50MB
stdout_logfile_backups  = 10
stdout_logfile          = /log/app.log

說明:
command:爲要後臺運行的shell命令
directory:指定command命令要執行的文件夾
user:執行命令的用戶
stdout_logfile:程序運行的日誌,報錯能夠在這裏看。
建立好子進程文件後,運行以下命令解鎖程序:app

# sudo unlink /run/supervisor.sock

再運行如下命令運行程序啓動爬蟲:python2.7

# supervisord

運行成功會有以下提示:scrapy

/usr/lib/python2.7/site-packages/supervisor/options.py:296: UserWarning: Supervisord is running 
as root and it is searching for its configuration file in default locations (including it
s current working directory); you probably want to specify a "-c" argument specifying an absolute path to a configuration file for improved security.
  'Supervisord is running as root and it is searching '

進程管理的相關命令

1) 查看全部子進程的狀態:ide

# supervisorctl status

awesome                             RUNNING    pid 2395, uptime 0:08:41

2)關閉、開啓指定的子進程:centos7

# supervisorctl stop zhoujy
awesome: stopped

3)關閉、開啓全部的子進程:spa

# supervisorctl stop all
awesome: stopped
# supervisorctl start all
awesome: started

總結

終於能夠愉快的爬蟲了呢!OvO

相關文章
相關標籤/搜索