<p>由于<code>raw_input</code>阻塞了您的代码,您可能需要将进程分成两个<a href="http://www.python-course.eu/threads.php" rel="nofollow noreferrer">threads</a>:一个是<code>main</code>,另一个是您在代码中创建的。由于线程以不可预知的顺序(有点)并发运行,您将无法准确地控制中断将到达主循环的线路。线程是一个非常棘手的部分,它需要大量的阅读、测试和检查为什么事情会以这种方式发生。。。你知道吗</p>
<p>另外,由于您不介意使用行,因此可以执行所谓的破坏性读取:将文件的内容加载到<code>lines</code>变量中,并继续使用<code>pop()</code>获取最后一个,直到要使用的行用完为止(或者标志已被激活)。检查<a href="https://docs.python.org/2/library/stdtypes.html#mutable-sequence-types" rel="nofollow noreferrer">pop()</a>方法在列表中的作用。注意<code>pop()</code>总是返回列表的最后一项。如果您希望按原始顺序打印项目,则必须使用以前<a href="https://stackoverflow.com/questions/3940128/how-can-i-reverse-a-list-in-python">reversed</a>列表中的<a href="https://stackoverflow.com/questions/2150108/efficient-way-to-shift-a-list-in-python">shift</a>或<code>pop</code>。你知道吗</p>
<pre><code>import threading
interrupt=None
def flag_activator():
global interrupt
interrupt = raw_input("(!!) Type yes when you wanna stop\n\n")
print "Oh gosh! The user input %s" % interrupt
th = threading.Thread(target=flag_activator)
th.start()
fr = open('q0.txt', 'r')
lines = fr.readlines()
fr.close()
while lines and interrupt != 'yes':
print "I read this line: %s" % lines.pop()
if len(lines) > 0:
print "Crap! There are still lines"
fw = open('q0.txt', 'w')
fw.writelines(lines)
fw.close()
</code></pre>
<p>现在,该代码将阻止您的终端,直到您在终端上键入<code>yes</code>。你知道吗</p>
<p>PS:不要忘记关闭打开的文件(如果不想显式调用<code>close()</code>,请参阅<code>with</code>语句<a href="http://effbot.org/zone/python-with-statement.htm" rel="nofollow noreferrer">here</a>和<a href="https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow noreferrer">here</a>)</p>
<h2>编辑(根据OP对我误解的评论):</h2>
<p>如果您希望确保在脚本突然停止时文件不会包含已处理的行,那么一种低效(但简单)的方法是:</p>
<ol>
<li>打开文件进行读写(每个操作需要不同的文件描述符)</li>
<li>将文件的所有行加载到一个变量中</li>
<li>处理第一行</li>
<li>从列表变量中删除该行</li>
<li>将剩余列表写入文件</li>
<li>重复此操作,直到不再加载<em>行</em>。你知道吗</li>
</ol>
<p>尽管所有这些打开/关闭文件的操作都非常非常低效,但它是这样的:</p>
<pre><code>done = False
while done == False:
with open("q0.txt", 'r') as fr, open("q0.txt", 'w') as fw:
lines = fr.readlines()
if len(lines) > 0:
print lines[0] # This would be your processing
del lines[0]
fw.writelines(lines)
else:
done = True
</code></pre>