如何永远运行一个脚本?

我需要永远在无限循环中运行 Python 程序。

目前我正在这样运行它-

#!/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电话? 有什么想法吗?

311507 次浏览

Yes, you can use a while True: loop that never breaks to run Python code continually.

However, you will need to put the code you want to run continually inside the loop:

#!/usr/bin/python


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

Also, time.sleep is used to suspend the operation of a script for a period of time. So, since you want yours to run continually, I don't see why you would use it.

How about this one?

import signal
signal.pause()

This will let your program sleep until it receives a signal from some other process (or itself, in another thread), letting it know it is time to do something.

for OS's that support select:

import select


# your code


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

sleep is a good way to avoid overload on the cpu

not sure if it's really clever, but I usually use

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

sleep method always returns None.

Here is the complete syntax,

#!/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

I have a small script interruptableloop.py that runs the code at an interval (default 1sec), it pumps out a message to the screen while it's running, and traps an interrupt signal that you can send with 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

When you run the script and then interrupt it you see this output, (the periods pump out on every pass of the loop):

[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

I know this is too old thread but why no one mentioned this

#!/usr/bin/python3
import asyncio


loop = asyncio.get_event_loop()
try:
loop.run_forever()
finally:
loop.close()

If you mean run as service then you can use any rest framework

from flask import Flask
class A:
def one(port):
app = Flask(__name__)
app.run(port = port)
        

call it:

one(port=1001)

it will always keep listening on 1001

 * Running on http://127.0.0.1:1001/ (Press CTRL+C to quit)