IT Share you

파이썬 프로그램을 영원히 실행하는 방법은 무엇입니까?

shareyou 2020. 11. 20. 17:19
반응형

파이썬 프로그램을 영원히 실행하는 방법은 무엇입니까?


파이썬 프로그램을 무한 루프에서 영원히 실행해야합니다 ..

현재 나는 이것을 다음과 같이 실행하고 있습니다-

#!/usr/bin/python

import time

# some python code that I want 
# to keep on running


# Is this the right way to run the python program forever?
# And do I even need this time.sleep call?
while True:
    time.sleep(5)

더 나은 방법이 있습니까? 아니면 time.sleep전화 가 필요한 가요? 이견있는 사람?


예, while True:중단되지 않는 루프를 사용하여 Python 코드를 지속적으로 실행할 수 있습니다 .

그러나 계속해서 실행하려는 코드를 루프 안에 넣어야합니다 .

#!/usr/bin/python

while True:
    # some python code that I want 
    # to keep on running

또한 일정 기간 동안 스크립트 작업 time.sleep일시 중지 하는 데 사용됩니다 . 그래서, 당신은 당신의 것이 계속 실행되기를 원하기 때문에 당신이 그것을 사용하는 이유를 모르겠습니다.


이건 어때?

import signal
signal.pause()

이것은 프로그램이 다른 프로세스 (또는 다른 스레드에서)로부터 신호를받을 때까지 잠자기 상태를 유지하여 무언가를 할 시간임을 알립니다.


수면은 CPU의 과부하를 피하는 좋은 방법입니다.

정말 영리한지는 모르겠지만 저는 보통

while(not sleep(5)):
    #code to execute

sleep 메서드는 항상 None을 반환합니다.


지원하는 OS의 경우 select:

import select

# your code

select.select([], [], [])

다음은 완전한 구문입니다.

#!/usr/bin/python3

import time 

def your_function():
    print("Hello, World")

while True:
    your_function()
    time.sleep(10) #make function to sleep for 10 seconds

일정한 간격 (기본값 1 초)으로 코드를 실행 하는 작은 스크립트 interruptableloop.py 가 있으며 실행중인 동안 화면에 메시지를 펌핑하고 CTL-C로 보낼 수있는 인터럽트 신호를 트랩합니다.

#!/usr/bin/python3
from interruptableLoop import InterruptableLoop

loop=InterruptableLoop(intervalSecs=1) # redundant argument
while loop.ShouldContinue():
   # some python code that I want 
   # to keep on running
   pass

스크립트를 실행 한 다음 중단하면 다음 출력이 표시됩니다 (루프의 모든 패스에서 기간이 펌핑 됨).

[py36]$ ./interruptexample.py
CTL-C to stop   (or $kill -s SIGINT pid)
......^C
Exiting at  2018-07-28 14:58:40.359331

interruptableLoop.py :

"""
    Use to create a permanent loop that can be stopped ...

    ... from same terminal where process was started and is running in foreground: 
        CTL-C

    ... from same user account but through a different terminal 
        $ kill -2 <pid> 
        or $ kill -s SIGINT <pid>

"""
import signal
import time
from datetime import datetime as dtt
__all__=["InterruptableLoop",]
class InterruptableLoop:
    def __init__(self,intervalSecs=1,printStatus=True):
        self.intervalSecs=intervalSecs
        self.shouldContinue=True
        self.printStatus=printStatus
        self.interrupted=False
        if self.printStatus:
            print ("CTL-C to stop\t(or $kill -s SIGINT pid)")
        signal.signal(signal.SIGINT, self._StopRunning)
        signal.signal(signal.SIGQUIT, self._Abort)
        signal.signal(signal.SIGTERM, self._Abort)

    def _StopRunning(self, signal, frame):
        self.shouldContinue = False

    def _Abort(self, signal, frame):
        raise 

    def ShouldContinue(self):
        time.sleep(self.intervalSecs)
        if self.shouldContinue and self.printStatus: 
            print( ".",end="",flush=True)
        elif not self.shouldContinue and self.printStatus:
            print ("Exiting at ",dtt.now())
        return self.shouldContinue

It's one of the only ways that I can think of. As to if it's appropriate, it depends on the use case - web servers and event loops sometimes do it like this. And no, you definitely do not need the time.sleep call.

참고URL : https://stackoverflow.com/questions/20170251/how-to-run-the-python-program-forever

반응형