我尝试将一些time.sleep(.1)
添加到我正在使用的循环中,但它似乎阻碍了执行(在我的CTRL+C
上点击IDLE
之后我得到time.sleep(.1)... KeyboardInterrupt
这证实了我的想法)
我尝试使用代码,发现在该行之后添加print()
可以防止暂停,但我仍然不明白为什么它首先发生...
在没有sleep
的情况下运行此操作我没有任何问题,所以我认为没有其他问题可以导致这种情况。对我有用的另一件事是使用sleep(0)
。我输入的任何正值都会再次阻止执行。
可疑行在循环结束时。
这是整个代码:
import time
def main():
with open(r'txt.bin') as f:
code = f.read()
data = [0 for i in range(22)]
data_p = 0
code_p = 0
reverse_code = code[::-1]
l = len(code)
flag = False
while code[code_p] != '.':
if data_p == 1:
#print('char read {0} {1}: {2}'.format(c, data_p,data[1]))
pass
c = code[code_p]
if c == '+':
data[data_p] += 1
data[data_p] %= 256
elif c == '-':
data[data_p] -= 1
if data[data_p] < 0:
data[data_p] = 255
elif c == '>':
data_p += 1
elif c == '<':
data_p -= 1
elif c == ',':
old = int(data[data_p])
data[data_p] = int(input('enter value at {0} (current value is {1}): '.format(data_p, data[data_p])))
print('replaced {0} with {1} at {2}'.format(old, data[data_p],data_p))
flag = True
elif c == '[':
if data[data_p] is 0:
old = int(code_p)
code_p = code.find(']', code_p)
print('started at loc {0} with val {1}\nnow at loc {2} with val {3}'.format(old, code[old], code_p, code[code_p]))
elif c == ']':
if data[data_p] is not 0:
reverse_code_p = l-1-code_p
old = int(code_p)
code_p = l-1-reverse_code.find('[', reverse_code_p)
print('started at loc {0} with val {1}\nnow at loc {2} with val {3}'.format(old, code[old], code_p, code[code_p]))
if flag:
time.sleep(1)
code_p += 1
print(data[data_p])
main()