Search code examples
pythonwindowsexittry-except

How to stop Python program by hand in Windows 10?


I have a try-except block of code in my program, that doesn't stop after running it. I tried spyder, sublima3, vs-code IDEs but none of them could stop it after running. How can I fix my code that I can stop it by pressing stop button?

import time 
import datetime
import requests
import pandas as pd
import os, sys


path = 'C:/Users/Admin/Desktop/filter/crawled/'
#list_file = str(os.listdir(path))
list_file = list(set([f for f in os.listdir (path)]))
list_file.sort(key=lambda x: os.stat(os.path.join(path, x)).st_mtime)
xlsx_file = []
for item in list_file:
    if item.endswith('.xlsx'):
        xlsx_file.append(item)
while(datetime.datetime.now().time() >= datetime.time(8,30,00) and datetime.datetime.now().time() <= datetime.time(15,30,00) ):
    try:
        name_file = path + str(datetime.datetime.now()).replace(':','-').replace(' ','_')
        point_index = name_file.find('.')
        name_file = name_file[:point_index ] + '.xlsx'
        link = 'http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0'
        resp = requests.get(link)
        output = open(name_file, 'wb')
        output.write(resp.content)
        output.close()    
    
        xl = pd.ExcelFile(name_file)
        print(xl.sheet_names)
        df1 = xl.parse()
        df1.columns = df1.iloc[1]
        df1 = df1.drop(1)
        print(df1.iloc[0][0])
        df1 = df1.drop(0)
        volume = 1000
        volume_str = 'حجم'
        name_str = 'نام'
        df1_volume = df1[df1[volume_str] > 1000][name_str]
        
        time.sleep(5)
        
    except:
        continue

Solution

  • The issue here is that you're bypassing all the exceptions by writing:

    except:
        continue
    
    # which is equivalent to:
    except BaseException:
        continue
    

    which also includes the exception KeyboardInterrupt and the reason to why you can't reliably stop it by using Ctrl + C (a keyboard interrupt).

    Although a bad practice, but what you might want is:

    except Exception:
        continue
    

    Exception does not include KeyboardInterrupt, so Ctrl + C will stop it always.

    Check the exception hierarchy here (Python docs) for more information.


    A good practice could be to handle exceptions on smaller code blocks, and handling specific exceptions, where you have a reason to believe that the data could be inappropriate.