如何在运行Python脚本的shell脚本中捕获Cntrl + C.

时间:2016-10-13 14:17:54

标签: python shell

我正在尝试编写一个运行Python程序的简单程序,并检查生成的输出文件:

#!/bin/bash

rm archived_sensor_data.json
python rethinkdb_monitor_batch.py
trap "gedit archived_sensor_data.json" 2

Python脚本rethinkdb_monitor_batch.py无限期运行,并以(仅附加模式)写入文件archived_sensor_data.json。为了每次都开始“干净的平板”,我想在每次运行之前删除该文件。然后在用Cntrl + C中断执行后,我想使用Gedit自动触发文件的打开。

问题是,当我按下Cntrl + C时,它似乎不会自动打开Gedit。 2不是正确的退出代码吗?

3 个答案:

答案 0 :(得分:2)

您可以通过捕获rethinkdb_monitor_batch.py内的信号来执行此操作,如下所示:

#!/usr/env/bin python

try:
    # your existing code here---let's assume it does the following:

    import time
    outfile = open( "archived_sensor_data.json", "wt" )  # NB: this already does the job of erasing previous content
    while True:
        outfile.write( "There's a horse in aisle five.\n" )
        time.sleep( 1 )
        outfile.write( "My house is full of traps.\n" )
        time.sleep( 1 )

except KeyboardInterrupt:
    print( "You pressed Ctrl-C" )

...然后包装脚本就是:

#!/bin/bash

python rethinkdb_monitor_batch.py
gedit archived_sensor_data.json

但实际上,为什么要使用包装器,当你可以在Python中完成所有操作时,替换最终的print()调用,如下所示:

except KeyboardInterrupt:
    os.execlp("gedit", "archived_sensor_data.json")

...然后直接从命令行调用Python脚本。

答案 1 :(得分:0)


    import signal
    import os
    os.system("rm archived_sensor_data.json")
    def signal_handler(signal, frame):
            print('You pressed Ctrl+C!')
            os.system("gedit archived_sensor_data.json")
    signal.signal(signal.SIGINT, signal_handler)
    #your remaining code
    #must be placed here



使用以下命令运行您的代码

$ python rethinkdb_monitor_batch.py

这必须解决你的问题
读取信号处理程序以获取更多信息

答案 2 :(得分:0)

其他答案涉及修改Python代码本身,这不太理想,因为我不希望它包含仅与测试相关的代码。相反,我发现以下bash脚本很有用:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
jQuery(document).ready(

  function(){
            jQuery('#twitter').animate({
                marginLeft : "-1060px"
            },1000);

});
</script>

这将在#!/bin/bash rm archived_sensor_data.json python rethinkdb_monitor_batch.py ; gedit archived_sensor_data.json 完成后运行gedit archived_sensor_data.json命令,无论它是否成功退出。