是否有适当的方法来创建一个脚本,该脚本通过文件夹中的文件循环并执行可以用CTRL C外部杀死的子过程?我有类似以下管道中嵌入的东西,当主过程被杀死时,我无法从命令行中进行ctrl c。
示例脚本:
import subprocess
import os
import sys
input_directory = sys.argv[1]
for file in os.listdir(os.path.abspath(input_directory)):
output = file + "_out.out"
command = ['somescript.py', file, output]
try:
subprocess.check_call(command)
except:
print "Command Failed"
我将执行程序:
Example_script.py /path/to/some/directory/containing/files/
当它在循环时,如果我看到命令失败,我想使用CtrlC。但是,尽管主要脚本一直是CtrlC。这样可以用Ctrl C杀死孩子(附加子过程)的这样的人?
任何帮助,或者指向我朝着方向指出。我目前正在寻找一种很好的方法。
您在尝试/块中所拥有的东西太允许了,因此按下 ctrl KeyboardInterrupt
exception还通过与print "Command Failed"
相同的例外处理程序来处理,并且现在在此处正确处理,该程序的流程通过for循环继续。您应该做的是:
- 用
except Exception:
替换except:
,以便不会被捕获KeyboardInterrupt
异常,以便任何时间 ctrl C 按下该程序将终止(包括subprocesses(包括subsprocesses)t处于某种不可终止状态); - 在
print
语句之后,break
从循环中脱离循环以防止执行进一步执行,如果这是您想要此程序的预期行为。
您可以捕获KeyboardInterrupt
,这样您就可以以任何方式处理 ctrl c 以任何方式。
import subprocess
import os
import sys
input_directory = sys.argv[1]
for file in os.listdir(os.path.abspath(input_directory)):
output = file + "_out.out"
command = ['somescript.py', file, output]
try:
subprocess.check_call(command)
except KeyboardInterrupt as e:
print "Interrupted"
sys.exit(1)
except:
print "Command Failed"
但是,我同意其他海报,因为您的例外太模糊了,您应该更具体地在可能和不会失败的情况下更具体。
我认为 ctrl z 也可以帮助您将执行推向背景并暂停。