1

I'm trying to exit from that code using CTRL F2 or or closing the process by stop button but the finally clause is never called. I would like when I stop the process to write the data to file.

  for root, dirnames, files in os.walk(r"c:\ahmed\SpeedFT-meter12\peakdata"):
        for name in files:
            timeStamps.append(name.replace('peakdata_','').replace('.bz2',''))
            print(name.replace('peakdata_','').replace('.bz2',''))
    i  = 0
    try:
        for dirpath, dirnames, filenames in os.walk(r"C:\ahmed\SpeedFT-meter12\peakdata"):
                for filename in [f for f in filenames if f.endswith(".bz2")]:
                    path = os.path.join(dirpath, filename)
                    print(path)
                    process_data(path, i)
    except KeyboardInterrupt:
        pass

    finally:
        print("writing data")
        general_pd['TimeStamp'] = TimeStamp
        general_pd['S_strain_HOY'] = S1
        general_pd['S_strain_HMY'] = S2
        general_pd['S_strain_HUY'] = S3
        general_pd['S_strain_ROX'] = S4
        general_pd['S_strain_LOX'] = S5
        general_pd['S_strain_LMX'] = S6
        general_pd['S_strain_LUX'] = S7
        general_pd['S_strain_VOY'] = S8
        general_pd['S_temp_HOY'] = T1
        general_pd['S_temp_HMY'] = T2
        general_pd['S_temp_HUY'] = T3
        general_pd['S_temp_LOX'] = T4
        general_pd['S_temp_LMX'] = T5
        general_pd['S_temp_LUX'] = T6
        writer = pd.ExcelWriter(r'c:\ahmed\median_data.xlsx', engine='xlsxwriter')
        # Convert the dataframe to an XlsxWriter Excel object.
        general_pd.to_excel(writer, sheet_name='Sheet1')
        # Close the Pandas Excel writer and output the Excel file.
        writer.save()
Slam
  • 8,112
  • 1
  • 36
  • 44
andre
  • 731
  • 2
  • 13
  • 27

1 Answers1

0

The reason you may miss your except/finally closure is that you're interrupting script out of your try/except (i.e. during for name in files: loop)

It's always help to debug any issue with minimal representative example, try running/stopping:

try:
    time.sleep(100)
except KeyboardInterrupt:
    print('Graceful stop')
finally:
    print('Cleanup')

If you'll still have issues with this, please provide your version of PyCharm an full exception message.

Slam
  • 8,112
  • 1
  • 36
  • 44
  • I wrote that minimal example, tried to kill the process by CTRL F2 and also by Stop button, it still never prints Graceful stop nor Cleanup – andre Oct 24 '18 at 08:31
  • Can you please look into `Run → Edit Configurations → → Execution → Emulate terminal in console output`, is it checked? – Slam Oct 24 '18 at 08:38
  • Sorry, than no idea how to help. I've just installed 2018.1.5 CE, can not reproduce this issue. Good luck fixing this. – Slam Oct 24 '18 at 08:46
  • can you rewrite the code, so that it works with the keyboard handeler ?\ – andre Oct 24 '18 at 08:52