[英]bash script Keyboard Interrupt hand over to Python Script
I have a bash script that starts my python script.我有一个 bash 脚本来启动我的 python 脚本。 Point of this is, that I hand over a lot of (sometimes changing) arguments to the python script.
重点是,我将很多(有时会更改)arguments 交给 python 脚本。 So I found it useful to start my python script with a bash script where I "save" my argument list.
所以我发现用 bash 脚本启动我的 python 脚本很有用,我在其中“保存”了我的参数列表。
#!/bin/bash
cd $(dirname $0)
python3 script.py [arg0] [arg1]
In my Python script I have the KeyboardInterrupt-Exception implemented which would save some open files and then exit the python script.在我的 Python 脚本中,我实现了 KeyboardInterrupt-Exception,它将保存一些打开的文件,然后退出 python 脚本。 Now my question: When I run the shell script I have to at least press 3-times Strg+C, get some python errors and it will stop.
现在我的问题是:当我运行 shell 脚本时,我必须至少按 3 次 Strg+C,得到一些 python 错误,它会停止。
Am i guessing right, that my Strg+C is not recognized by python, but by the shell script instead?我猜对了吗,我的 Strg+C 不被 python 识别,而是被 shell 脚本识别? Is there a way to hand over the Keyboard Interrupt from the shell script to the python script running in it?
有没有办法将键盘中断从 shell 脚本移交给其中运行的 python 脚本?
btw: the python script is running an infinite loop (if this is important)顺便说一句:python 脚本正在运行无限循环(如果这很重要)
Python script looks like this for the exception. Python 脚本看起来像这样的异常。 As pointed out, it runs an infinite loop.
正如所指出的,它运行一个无限循环。
while True:
try:
#doing stuff here
except KeyboardInterrupt:
for file in files:
file.close()
break
try "trap" command to assign custom action on signals.尝试“trap”命令为信号分配自定义操作。 For Ctrl-C you need to ignore SIGINT, also you can ignore SIGTERM:
对于 Ctrl-C 你需要忽略 SIGINT,你也可以忽略 SIGTERM:
function ignore_ctrlc() {
echo "ignored"
}
trap ignore_ctrlc SIGINT SIGTERM
declare -i counter=0
while true; do
echo "sleep for 1 sec"
sleep 1
counter+=1
[[ $counter -gt 10 ]] && exit 0
done
In the script above, Ctrl-C will interrupt executing command (most probability it will be sleep 1), but will not interrupt the script itself.在上面的脚本中,Ctrl-C 将中断执行命令(最有可能是 sleep 1),但不会中断脚本本身。 In your case, your python script should ignore Ctrl-C, so I think it will be ignored at all.
在你的情况下,你的 python 脚本应该忽略 Ctrl-C,所以我认为它会被忽略。
If that's your entire script, why not tail-call python
?如果这是您的整个脚本,为什么不尾调用
python
? Bash will get completely out of the way. Bash 将完全避开。
#!/bin/bash
cd $(dirname $0)
exec python3 script.py [arg0] [arg1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.