我对python很新,我遇到了以下问题.我有一个脚本,它逐个处理文件,并根据输入文件名将输出写入单独的文件.有时我需要打破脚本,但我想让它完成当前文件的处理,然后终止(以避免信息不完整的结果文件).如何在python中编写此行为?
这是我试过的.
a)尝试 - 除外块
x = 1
print "Script started."
while True:
try:
print "Processing file #",x,"started...",
# do something time-cosnuming
time.sleep(1)
x += 1
print " finished."
except KeyboardInterrupt:
print "Bye"
print "x=",x
sys.exit()
sys.exit()
Run Code Online (Sandbox Code Playgroud)
输出:
Script started.
Processing file # 1 started... finished.
Processing file # 2 started... finished.
Processing file # 3 started... Bye
x= 3
Run Code Online (Sandbox Code Playgroud)
迭代#3未正常完成.
b)sys.excepthook
OriginalExceptHook = sys.excepthook
def NewExceptHook(type, value, traceback):
global Terminator
Terminator = True
if type == KeyboardInterrupt:
#exit("\nExiting by …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用正则表达式从PHP中的UTF8字符串中删除重复的空白字符.这个正则表达式
$txt = preg_replace( '/\s+/i' , ' ', $txt );
Run Code Online (Sandbox Code Playgroud)
通常工作正常,但有些字符串有西里尔字母"Р",更换后拧紧.经过小规模的研究后,我意识到这个字母被编码为\ x {D0A0},并且因为\ xA0是ASCII中的非破坏空格,所以正则表达式用\ x20替换它并且该字符不再有效.
有关如何在PHP中使用正则表达式正确执行此操作的任何想法?