Python Selenium脚本执行中途print无法实时输出到命令行如何解决
问题原因
你遇到的print输出延迟是Python默认的输出缓冲机制导致的:默认情况下Python会把标准输出的内容先暂存在缓冲区,等缓冲区满、脚本结束或者遇到输入操作(比如你用的input())时才会批量把内容刷到命令行显示,所以只有触发输入操作时才会提前输出内容,其他时候要等driver退出、脚本跑完才会显示打印内容。
解决方案
- 方案1:给
print()函数添加flush=True参数,强制每次print后立刻刷新缓冲区,无需修改其他运行配置,是最灵活的方案。
修改后的代码示例:
first_run = res_loop(url, tr) if first_run > 0: xml_input = first_run else: loop_decision = input("Do you want to run the script until a time slot is found?\n") if loop_decision[0].upper() == 'Y': loop_output = 0 loop_ct = 1 while loop_output == 0 and res_date_obj > datetime.now().date() and loop_ct <= 5: print(loop_ct, flush=True) time.sleep(5) # time.sleep(60) loop_output = res_loop(url, tr) loop_ct += 1 if loop_ct % 2 == 0: print(f"We've ran this script {loop_ct} times and haven't found anything, but we're still trying!", flush=True) if loop_output > 0: xml_input = loop_output else: print("Sorry, no time slots became available.", flush=True) driver.quit()
- 方案2:运行Python脚本时添加
-u参数,全局禁用标准输出/标准错误的缓冲机制,不需要修改代码。运行命令如下:python -u 你的脚本文件名.py - 方案3:如果后续替换为logging模块做日志输出,可以在初始化日志时设置流的自动刷新规则,也能实现实时输出。
内容的提问来源于stack exchange,提问作者srodman1
相关产品推荐
相关产品推荐

