简体   繁体   English

在bash上运行python脚本时如何抑制KeyboardInterrupt输出?

[英]How to suppress KeyboardInterrupt output when running a python script on bash?

I decide to run a python script from my bash terminal prompt, eg running $ python my_script.py . 我决定从bash终端提示符运行python脚本,例如,运行$ python my_script.py

I then decide to press Ctrl-C to kill this active process. 然后,我决定按Ctrl-C终止此活动进程。

Then, the process dies, and some output error comes to the terminal, that may look like: 然后,该进程终止,并且终端出现一些输出错误,看起来可能是这样的:

^C
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
KeyboardInterrupt

How can I suppress this output from the bash/terminal side while still using Ctrl-C . 如何在仍然使用Ctrl-C同时从bash / terminal端抑制此输出。

From this comment I learned that you can use Ctrl-\\ to quit the process, which is apparently different than Ctrl-C . 通过此注释,我了解到可以使用Ctrl-\\退出该过程,这显然与Ctrl-C不同。 It seems to suppress any output. 似乎抑制了任何输出。

However, if I simply run $ python and run some code within the interactive python shell, using Ctrl-\\ will completely quit the Python shell process, while Ctrl-C just kills that code that I had just execute (like a for loop) but preserves the Python shell process. 但是,如果我只运行$ python并在交互式python shell中运行一些代码,则使用Ctrl-\\会完全退出Python shell进程,而Ctrl-C只会杀死我刚刚执行的代码(例如for循环),但是保留Python Shell进程。

You can do python script.py 2>/dev/null since you're using bash. 您可以执行python script.py 2>/dev/null因为您正在使用bash。

The 2 means it sends stderr to a special file /dev/null which is always empty, to which this script will now send its output to. 2表示它将stderr发送到一个特殊文件/ dev / null ,该文件始终为空,此脚本现在将其输出发送到该文件。

If you had no 2 , it would suppress standard output (ie stdout ) but not errors. 如果没有2 ,它将抑制标准输出(即stdout ),但不会出错。

If you wanted to suppress both, you could do > /dev/null 2>&1 , since 1 is stdout, and stdout is now being routed to devnull. 如果要同时抑制这两者,则可以> /dev/null 2>&1 ,因为1是stdout,并且stdout现在被路由到devnull。

Essentially, you are sending the error traceback, instead of to the standard stderr location (your screen), to a blank file. 本质上,您是将错误回溯发送到空白文件,而不是发送到标准stderr位置(您的屏幕)。

You can use a try-except block: 您可以使用try-except块:
Here in the below code, I am just printing some numbers as an example, replace that with your code: 在下面的代码中,我仅以打印一些数字为例,将其替换为您的代码:


import sys
try:
    # your code
    for i in range(1000000):
        print(i)

except KeyboardInterrupt:
    sys.exit(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM