찾다
백엔드 개발파이썬 튜토리얼Python使用Supervisor来管理进程的方法

本文实例讲述了Python使用Supervisor来管理进程的方法。分享给大家供大家参考。具体分析如下:

Supervisor可以启动、停止、重启*nix系统中的程序。也可以重启崩溃的程序。

supervisord的一个守护进程,用于将指定的进程当做子进程来运行。

supervisorctl是一个客户端程序,可以查看日志并通过统一的会话来控制进程。

看例子:

我们写了一个py脚本,用于往log文件中记录一条当前的时间。

root@ubuntu:/home/zoer# cat daemon.py
#!/usr/bin/env python
import time
import os
time.sleep(1)
f=open("log",'a')
t=time.time()
f.write(str(t))
f.write("\n")
f.close()

安装过程就不说了。

安装完毕supervisor之后【将配置文件放在/etc下】。修改配置文件,在最后增加如下内容:

[program:ddd]
command=/home/zoer/daemon.py
autorestart=true

然后我们启动supervisor并启动daemon.py的执行。

root@ubuntu:/home/zoer# supervisord 
/usr/local/lib/python2.7/dist-packages/supervisor-3.0b1-py2.7.egg/supervisor/options.py:286: UserWarning: Supervisord is running as root and it is searching for its configuration file in default locations (including its 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 ' 
root@ubuntu:/home/zoer# supervisorctl 
ddd               STARTING   
supervisor> start ddd 
ddd: ERROR (already started) 
supervisor> stop ddd 
ddd: stopped 
supervisor> start ddd 
ddd: started 
supervisor>

从上面的例子中,看到,可以通过start或者stop命令来启动或者停止ddd这个进程。ddd这里就是我们在配置文件中增加的内容(daemon.py这个脚本)。

也可以使用restart。如下:

supervisor> restart  ddd
ddd: stopped
ddd: started

下面我们测试一下,假设说我们手动kill掉了ddd这个进程,那么ddd会自动恢复执行吗?

为了做实验,把代码修改如下:

root@ubuntu:/home/zoer# cat daemon.py  
#!/usr/bin/env python 
import time 
import os 
while True: 
  time.sleep(1) 
  f=open("log",'a') 
  t=time.time() 
  f.write(str(t)) 
  f.write("\n") 
  f.close()

通过ps可以找到这个进程的id:

root   9354 0.2 0.4 10924 4200 ?    S  23:16  0:00 python /home/zoer/daemon.py 
root   9395 0.0 0.0  4392  832 pts/3  S+  23:17  0:00 grep --color=auto daemon 
root@ubuntu:/home/zoer#

看下面的操作:

root@ubuntu:/home/zoer# rm log;touch log;kill 9354
root@ubuntu:/home/zoer# cat log 
1364710712.51 
root@ubuntu:/home/zoer# cat log 
1364710712.51 
1364710713.51 
root@ubuntu:/home/zoer# cat log 
1364710712.51 
1364710713.51 
root@ubuntu:/home/zoer# cat log 
1364710712.51 
1364710713.51 
1364710714.52 
root@ubuntu:/home/zoer# cat log 
1364710712.51 
1364710713.51 
1364710714.52 
1364710715.52

删除了log文件,并且重新创建。然后干掉了daemon.py的那个进程。会发现log内容又重新有新的内容了。再次ps查看进程号。

root   9429 0.1 0.4 10924 4200 ?    S  23:18  0:00 python /home/zoer/daemon.py 
root   9440 0.0 0.0  4392  828 pts/3  S+  23:19  0:00 grep --color=auto daemon 
root@ubuntu:/home/zoer#

会发现进程号已经变成9429了。说明supervisor已经重启了被干掉了的进程。

希望本文所述对大家的Python程序设计有所帮助。

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
파이썬 어레이에 어떤 데이터 유형을 저장할 수 있습니까?파이썬 어레이에 어떤 데이터 유형을 저장할 수 있습니까?Apr 27, 2025 am 12:11 AM

PythonlistsCanstoreAnyDatAtype, ArrayModuLearRaysStoreOneType 및 NUMPYARRAYSAREFORNUMERICALPUTATION.1) LISTSAREVERSATILEBUTLESSMEMORY-EFFICENT.2) ARRAYMODUERRAYRAYRAYSARRYSARESARESARESARESARESARESAREDOREDORY-UNFICEDONOUNEOUSDATA.3) NumpyArraysUraysOrcepperperperperperperperperperperperperperperperferperferperferferpercient

파이썬 어레이에 잘못된 데이터 유형의 값을 저장하려고하면 어떻게됩니까?파이썬 어레이에 잘못된 데이터 유형의 값을 저장하려고하면 어떻게됩니까?Apr 27, 2025 am 12:10 AM

whenyouattempttoreavalueofthewrongdatatypeinapythonaphonarray, thisiSdueTotheArrayModule의 stricttyPeenforcement, theAllElementStobeofthesAmetypecified bythetypecode.forperformancersassion, arraysaremoreficats the thraysaremoreficats thetheperfication the thraysaremorefications는

Python Standard Library의 일부는 무엇입니까? 목록 또는 배열은 무엇입니까?Python Standard Library의 일부는 무엇입니까? 목록 또는 배열은 무엇입니까?Apr 27, 2025 am 12:03 AM

Pythonlistsarepartoftsandardlardlibrary, whileraysarenot.listsarebuilt-in, 다재다능하고, 수집 할 수있는 반면, arraysarreprovidedByTearRaymoduledlesscommonlyusedDuetolimitedFunctionality.

스크립트가 잘못된 파이썬 버전으로 실행되는지 확인해야합니까?스크립트가 잘못된 파이썬 버전으로 실행되는지 확인해야합니까?Apr 27, 2025 am 12:01 AM

thescriptIsrunningwithHongpyThonversionDueCorRectDefaultTerpretersEttings.tofixThis : 1) checktheDefaultPyThonVersionUsingPyThon-VersionorPyThon3- version.2) usvirtual-ErondmentsBythePython.9-Mvenvmyenv, 활성화, 및 파괴

파이썬 어레이에서 수행 할 수있는 일반적인 작업은 무엇입니까?파이썬 어레이에서 수행 할 수있는 일반적인 작업은 무엇입니까?Apr 26, 2025 am 12:22 AM

PythonArraysSupportVariousOperations : 1) SlicingExtractsSubsets, 2) 추가/확장 어드먼트, 3) 삽입 값 삽입 ATSpecificPositions, 4) retingdeletesElements, 5) 분류/ReversingChangesOrder 및 6) ListsompectionScreateNewListSbasedOnsistin

어떤 유형의 응용 프로그램에서 Numpy Array가 일반적으로 사용됩니까?어떤 유형의 응용 프로그램에서 Numpy Array가 일반적으로 사용됩니까?Apr 26, 2025 am 12:13 AM

NumpyArraysareSentialplosplicationSefficationSefficientNumericalcomputationsanddatamanipulation. Theyarcrucialindatascience, MachineLearning, Physics, Engineering 및 Financeduetotheiribility에 대한 handlarge-scaledataefficivally. forexample, Infinancialanyaly

파이썬의 목록 위의 배열을 언제 사용 하시겠습니까?파이썬의 목록 위의 배열을 언제 사용 하시겠습니까?Apr 26, 2025 am 12:12 AM

UseanArray.ArrayOveralistInpyThonWhendealingwithhomogeneousData, Performance-CriticalCode, OrinterFacingwithCcode.1) HomogeneousData : ArraysSaveMemorywithtypepletement.2) Performance-CriticalCode : arraysofferbetterporcomanceFornumericalOperations.3) Interf

모든 목록 작업은 배열에 의해 지원됩니까? 왜 또는 왜 그렇지 않습니까?모든 목록 작업은 배열에 의해 지원됩니까? 왜 또는 왜 그렇지 않습니까?Apr 26, 2025 am 12:05 AM

아니요, NOTALLLISTOPERATIONARESUPPORTEDBYARRARES, andVICEVERSA.1) ArraySDONOTSUPPORTDYNAMICOPERATIONSLIKEPENDORINSERTWITHUTRESIGING, WHITHIMPACTSPERFORMANCE.2) ListSDONOTEECONSTANTTIMECOMPLEXITEFORDITITICCESSLIKEARRAYSDO.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는