如何在Windows 10 中手动停止Python 程序?

How to stop Python program by hand in Windows 10?

我的程序中有一个 try-except 代码块,它在 运行 之后不会停止。我尝试了 spyder, sublima3, vs-code 个 IDE,但其中 none 个可以在 运行 之后停止它。我怎样才能修复我的代码,我可以通过按停止按钮来停止它?

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

要停止程序,在 windows 中只需按 Control + C.

在 Unix 风格的 shell 环境中,您可以按 CTRL + Z 暂停当前正在控制的任何进程控制台。

这里的问题是您通过编写来绕过所有异常:

except:
    continue

# which is equivalent to:
except BaseException:
    continue

其中还包括异常 KeyboardInterrupt 以及无法使用 Ctrl + C(键盘中断)可靠地停止它的原因。

虽然是不好的做法,但你可能想要的是:

except Exception:
    continue

Exception 不包含 KeyboardInterrupt,所以 Ctrl + C 会一直停止它。

查看异常层次结构 here (Python docs) 了解更多信息。


一个好的做法是在较小的代码块上处理异常,并在您有理由相信数据可能不合适的情况下处理特定的异常。