2015-12-30 112 views
1

假设我编写了这样的程序。如何在不停止程序的情况下更改参数

# run the program until the user gives a "stop" input 
usrinpt=""` 
n=1 
while usrinpt!="stop": 
    n+=1 
    ---- do-something ----- 
    ---- do-something ----- 
    ---- do-something ----- 
print n # print the number of loops it has gone through. 

现在程序将运行,直到我手动将参数usrinpt更改为“stop”。但是使用raw_input会在每一步都停止模拟,这不是我想要的。

那么,有没有办法在不停止仿真的情况下更改usrinpt

回答

1

一个使用线程更复杂的解决方案:

from __future__ import print_function # Python 2/3 compatibility 

import sys 
from time import sleep 
from threading import Thread 

if sys.version_info.major < 3: 
    input = raw_input 

def do_something(): 
    # doing the work 
    sleep(1) 

usrinpt = '' 

def main(): 
    n = 1 
    while usrinpt != 'stop': 
     n += 1 
     do_something() 
    print('\nnumber of loops', n) 

thread = Thread(target=main) 
thread.start() 

while True: 
    print('Enter "stop" to terminate program') 
    usrinpt = input().strip().lower() 
    if usrinpt == 'stop': 
     break 

thread.join() 

示例程序运行:

python stop.py 
Enter "stop" to terminate program 
hello 
Enter "stop" to terminate program 
stop 

number of loops 6 
1

您可以搭乘KeyboardInterrupt例外:

from __future__ import print_function # Python 2/3 compatibility 

n = 1 
try: 
    while True: 
     n += 1 
except KeyboardInterrupt: 
    print('\nnumber of loops', n) 

<CTRL>-<C>程序打印迭代次数和持续的用户类型。

+0

这肯定会工作,但有没有办法做到这一点,而不使用中断 –

相关问题