擅长:python、mysql、java
<p>只需安装一个信号处理器signal.SIGTERM信号-在它里面,你可以在你的程序中设置一个状态变量,当你处理完每一个文件时你会检查它。在</p>
<p>实际上非常简单-请参阅文档:<a href="https://docs.python.org/2/library/signal.html" rel="nofollow">https://docs.python.org/2/library/signal.html</a>。在</p>
<pre><code>import os
import signal
terminate = False
for filename in os.listdir("<your dir>"):
if terminate:
break
process_next_file(filename)
def handler(signum, frame):
global terminate
print("Termination requested")
terminate = True
signal.signal(signal.SIGTERM, handler)
</code></pre>
<p>(此外,您还可以使用其他信号—例如,当用户按ctrl+C时使用SIGINT)</p>