假设我写了这样的程序。
# 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
更改为"停止"。但是使用raw_input将在每个步骤停止模拟,这不是我想要的。
那么,有没有办法在不停止模拟的情况下更改usrinpt
?
答案 0 :(得分: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>
时,程序会打印迭代次数并继续。
答案 1 :(得分:1)
使用线程的更复杂的解决方案:
describe MyClass do
before { @my_class = MyClass.new }
describe '#update' do
it 'should correctly update the value' do
@my_class.update('some_value')
expect(@my_class.ary).to equal(['some_value'])
示例程序运行:
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()