使程序在python中无限期运行

时间:2022-08-22 18:10:37

Is there any way to make a function (the ones I'm thinking of are in the style of the simple ones I've made which generate the fibonnacci sequence from 0 to a point, and all the primes between two points) run indefinitely. E.g. until I press a certain key or until a time has passed, rather than until a number reaches a certain point?

是否有任何方法可以创建一个函数(我想到的是我所做的简单样式,它们生成从0到点的fibonnacci序列,以及两点之间的所有素数)无限运行。例如。直到我按某个键或直到某个时间过去,而不是直到一个数字达到某一点?

Also, if it is based on time then is there any way I could just extend the time and start it going from that point again, rather than having to start again from 0? I am aware there is a time module, i just don't know much about it.

此外,如果它是基于时间,那么有什么方法我可以延长时间并再次从那一点开始,而不是必须从0开始?我知道有一个时间模块,我只是不太了解它。

7 个解决方案

#1


1  

The simplest way is just to write a program with an infinite loop, and then hit control-C to stop it. Without more description it's hard to know if this works for you.

最简单的方法就是编写一个带有无限循环的程序,然后点击control-C来阻止它。没有更多描述,很难知道这是否适合您。

If you do it time-based, you don't need a generator. You can just have it pause for user input, something like a "Continue? [y/n]", read from stdin, and depending on what you get either exit the loop or not.

如果你这样做是基于时间的,你不需要发电机。您可以让它暂停用户输入,例如“继续?[y / n]”,从标准输入读取,并根据您获得的是否退出循环。

#2


1  

You could use a generator for this:

您可以使用生成器:

def finished():
    "Define your exit condition here"
    return ...

def count(i=0):
    while not finished():
        yield i
        i += 1

for i in count():
    print i

If you want to change the exit condition you could pass a value back into the generator function and use that value to determine when to exit.

如果要更改退出条件,可以将值传递回生成器函数,并使用该值确定何时退出。

#3


0  

As in almost all languages:

与几乎所有语言一样:

while True:
  # check what you want and eventually break
  print nextValue()

The second part of your question is more interesting:

你问题的第二部分更有趣:

Also, if it is based on time then is there anyway I could just extend the time and start it going from that point again rather than having to start again from 0

此外,如果它是基于时间,那么无论如何我可以只是延长时间并从那一点再次开始,而不是从0开始

you can use a yield instead of return in the function nextValue()

你可以在函数nextValue()中使用yield而不是return

#4


0  

If you use a child thread to run the function while the main thread waits for character input it should work. Just remember to have something that stops the child thread (in the example below the global runthread)

如果在主线程等待字符输入时使用子线程来运行该函数,它应该可以工作。只记得有一些东西可以阻止子线程(在全局runthread下面的示例中)

For example:

import threading, time
runthread = 1
def myfun():
   while runthread:
      print "A"
      time.sleep(.1)

t = threading.Thread(target=myfun)
t.start()
raw_input("")
runthread = 0
t.join()

does just that

做到了那一点

#5


0  

If you really want your function to run and still wants user (or system) input, you have two solutions:

如果您真的希望您的功能运行并仍然需要用户(或系统)输入,那么您有两个解决方案:

  1. multi-thread
  2. multi-process

It will depend on how fine the interaction. If you just want to interrupt the function and don't care about the exit, then multi-process is fine.

这将取决于互动的精细程度。如果您只想中断该功能而不关心退出,那么多进程就可以了。

In both cases, you can rely on some shared resources (file or shared memory for multi-thread, variable with associated mutex for multi-thread) and check for the state of that resource regularly in your function. If it is set up to tell you to quit, just do it.

在这两种情况下,您都可以依赖一些共享资源(多线程的文件或共享内存,多线程的关联互斥锁变量),并在您的函数中定期检查该资源的状态。如果设置为告诉您退出,只需执行此操作即可。

Example on multi-thread:

多线程示例:

from threading import Thread, Lock
from time import sleep

class MyFct(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.mutex = Lock()
        self._quit = False

    def stopped(self):
        self.mutex.acquire()
        val = self._quit
        self.mutex.release()
        return val

    def stop(self):
        self.mutex.acquire()
        self._quit = True
        self.mutex.release()

    def run(self):
        i = 1
        j = 1
        print i
        print j
        while True:
            if self.stopped():
                return
            i,j = j,i+j
            print j

def main_fct():
    t = MyFct()
    t.start()
    sleep(1)
    t.stop()
    t.join()
    print "Exited"

if __name__ == "__main__":
    main_fct()

#6


0  

If you want to exit based on time, you can use the signal module's alarm(time) function, and the catch the SIGALRM - here's an example http://docs.python.org/library/signal.html#example

如果你想根据时间退出,你可以使用信号模块的闹钟(时间)功能,并抓住SIGALRM - 这是一个例子http://docs.python.org/library/signal.html#example

You can let the user interrupt the program in a sane manner by catching KeyboardInterrupt. Simply catch the KeyboardInterrupt exception from outside you main loop, and do whatever cleanup you want.

您可以通过捕获KeyboardInterrupt让用户以理智的方式中断程序。只需从主循环外部捕获KeyboardInterrupt异常,并执行所需的任何清理。

If you want to continue later where you left off, you will have to add some sort persistence. I would pickle a data structure to disk, that you could read back in to continue the operations.

如果您想在上次停止的地方继续,则必须添加一些排序持久性。我会将数据结构挑选到磁盘,您可以读回来继续操作。

I haven't tried anything like this, but you could look into using something like memoizing, and caching to the disk.

我没有尝试过这样的东西,但是你可以考虑使用memoizing和缓存到磁盘之类的东西。

#7


-1  

You could do something like this to generate fibonnacci numbers for 1 second then stop.

你可以做这样的事情来生成1秒钟的斐波那契数字然后停止。

fibonnacci = [1,1]
stoptime = time.time() + 1 # set stop time to 1 second in the future
while time.time() < stoptime:
  fibonnacci.append(fibonnacci[-1]+fibonnacci[-2])

print "Generated %s numbers, the last one was %s." % (len(fibonnacci),fibonnacci[-1])

I'm not sure how efficient it is to call time.time() in every loop - depending on the what you are doing inside the loop, it might end up taking a lot of the performance away.

我不确定在每个循环中调用time.time()是多么有效 - 取决于你在循环中做的事情,它可能最终会带走很多性能。

#1


1  

The simplest way is just to write a program with an infinite loop, and then hit control-C to stop it. Without more description it's hard to know if this works for you.

最简单的方法就是编写一个带有无限循环的程序,然后点击control-C来阻止它。没有更多描述,很难知道这是否适合您。

If you do it time-based, you don't need a generator. You can just have it pause for user input, something like a "Continue? [y/n]", read from stdin, and depending on what you get either exit the loop or not.

如果你这样做是基于时间的,你不需要发电机。您可以让它暂停用户输入,例如“继续?[y / n]”,从标准输入读取,并根据您获得的是否退出循环。

#2


1  

You could use a generator for this:

您可以使用生成器:

def finished():
    "Define your exit condition here"
    return ...

def count(i=0):
    while not finished():
        yield i
        i += 1

for i in count():
    print i

If you want to change the exit condition you could pass a value back into the generator function and use that value to determine when to exit.

如果要更改退出条件,可以将值传递回生成器函数,并使用该值确定何时退出。

#3


0  

As in almost all languages:

与几乎所有语言一样:

while True:
  # check what you want and eventually break
  print nextValue()

The second part of your question is more interesting:

你问题的第二部分更有趣:

Also, if it is based on time then is there anyway I could just extend the time and start it going from that point again rather than having to start again from 0

此外,如果它是基于时间,那么无论如何我可以只是延长时间并从那一点再次开始,而不是从0开始

you can use a yield instead of return in the function nextValue()

你可以在函数nextValue()中使用yield而不是return

#4


0  

If you use a child thread to run the function while the main thread waits for character input it should work. Just remember to have something that stops the child thread (in the example below the global runthread)

如果在主线程等待字符输入时使用子线程来运行该函数,它应该可以工作。只记得有一些东西可以阻止子线程(在全局runthread下面的示例中)

For example:

import threading, time
runthread = 1
def myfun():
   while runthread:
      print "A"
      time.sleep(.1)

t = threading.Thread(target=myfun)
t.start()
raw_input("")
runthread = 0
t.join()

does just that

做到了那一点

#5


0  

If you really want your function to run and still wants user (or system) input, you have two solutions:

如果您真的希望您的功能运行并仍然需要用户(或系统)输入,那么您有两个解决方案:

  1. multi-thread
  2. multi-process

It will depend on how fine the interaction. If you just want to interrupt the function and don't care about the exit, then multi-process is fine.

这将取决于互动的精细程度。如果您只想中断该功能而不关心退出,那么多进程就可以了。

In both cases, you can rely on some shared resources (file or shared memory for multi-thread, variable with associated mutex for multi-thread) and check for the state of that resource regularly in your function. If it is set up to tell you to quit, just do it.

在这两种情况下,您都可以依赖一些共享资源(多线程的文件或共享内存,多线程的关联互斥锁变量),并在您的函数中定期检查该资源的状态。如果设置为告诉您退出,只需执行此操作即可。

Example on multi-thread:

多线程示例:

from threading import Thread, Lock
from time import sleep

class MyFct(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.mutex = Lock()
        self._quit = False

    def stopped(self):
        self.mutex.acquire()
        val = self._quit
        self.mutex.release()
        return val

    def stop(self):
        self.mutex.acquire()
        self._quit = True
        self.mutex.release()

    def run(self):
        i = 1
        j = 1
        print i
        print j
        while True:
            if self.stopped():
                return
            i,j = j,i+j
            print j

def main_fct():
    t = MyFct()
    t.start()
    sleep(1)
    t.stop()
    t.join()
    print "Exited"

if __name__ == "__main__":
    main_fct()

#6


0  

If you want to exit based on time, you can use the signal module's alarm(time) function, and the catch the SIGALRM - here's an example http://docs.python.org/library/signal.html#example

如果你想根据时间退出,你可以使用信号模块的闹钟(时间)功能,并抓住SIGALRM - 这是一个例子http://docs.python.org/library/signal.html#example

You can let the user interrupt the program in a sane manner by catching KeyboardInterrupt. Simply catch the KeyboardInterrupt exception from outside you main loop, and do whatever cleanup you want.

您可以通过捕获KeyboardInterrupt让用户以理智的方式中断程序。只需从主循环外部捕获KeyboardInterrupt异常,并执行所需的任何清理。

If you want to continue later where you left off, you will have to add some sort persistence. I would pickle a data structure to disk, that you could read back in to continue the operations.

如果您想在上次停止的地方继续,则必须添加一些排序持久性。我会将数据结构挑选到磁盘,您可以读回来继续操作。

I haven't tried anything like this, but you could look into using something like memoizing, and caching to the disk.

我没有尝试过这样的东西,但是你可以考虑使用memoizing和缓存到磁盘之类的东西。

#7


-1  

You could do something like this to generate fibonnacci numbers for 1 second then stop.

你可以做这样的事情来生成1秒钟的斐波那契数字然后停止。

fibonnacci = [1,1]
stoptime = time.time() + 1 # set stop time to 1 second in the future
while time.time() < stoptime:
  fibonnacci.append(fibonnacci[-1]+fibonnacci[-2])

print "Generated %s numbers, the last one was %s." % (len(fibonnacci),fibonnacci[-1])

I'm not sure how efficient it is to call time.time() in every loop - depending on the what you are doing inside the loop, it might end up taking a lot of the performance away.

我不确定在每个循环中调用time.time()是多么有效 - 取决于你在循环中做的事情,它可能最终会带走很多性能。