使用schedule库时函数内print语句无法输出的问题求助
解决schedule定时任务中print无输出的问题
我来帮你拆解并解决这个问题:
问题根源
当你直接调用api_request时,程序在主线程的交互式环境中运行,print的输出会被立即刷新到终端。但用schedule跑定时任务时,任务是在单独的后台线程里执行的,此时标准输出(stdout)的缓冲策略会变化——默认是块缓冲,导致print的内容不会立刻显示,甚至可能一直被缓冲着看不到输出。
另外还有个潜在隐患:你的函数里有input()调用,在自动化定时任务场景下,这个交互式输入会导致任务线程阻塞(没有用户输入的话会一直卡着),你说能正常生成Excel可能是环境特殊,但这个写法完全不符合自动化需求,必须去掉。
具体解决方案
1. 给print添加flush=True参数
修改所有print语句,强制刷新输出缓冲,确保内容立刻显示:
import time import schedule import datetime import requests import pandas as pd def api_request(*args): print('Initializing API GET request at', flush=True) print(datetime.datetime.now(), flush=True) # Requests a connection to the EPA AirNow API & prints the response code response_api = requests.get('https://www.airnowapi.org/aq/data/?startDate=2022-03-18T02&endDate=2022-03-18T03' '¶meters=PM25&BBOX=-154.468155,62.158926,-143.042374,' '66.769032&dataType=C&format=application/json&verbose=1&monitorType=0' '&includerawconcentrations=0&API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxx') print(response_api.status_code, flush=True) # Imports data from the EPA AirNow server data_import = response_api.text # Prints imported data print(data_import, flush=True) print(flush=True) # 移除交互式输入,适配自动化场景 # print('Please press \'enter\' to export the data to an Excel file') # input() # Converts data from JSON format to an Excel sheet (xlsx) df_json = pd.read_json(data_import, orient='records') df_json.to_excel('datafile.xlsx') print('Data exported to .xlsx file at', flush=True) print(datetime.datetime.now(), flush=True) return # Schedules the api_request function to run daily at 1am. schedule.every().day.at('01:00').do(api_request, 'It is 01:00, initializing api_request function.') while True: schedule.run_pending() time.sleep(60)
2. (可选)全局设置自动刷新
如果你不想逐个修改print,可以在代码开头添加:
import sys sys.stdout.flush()
不过更推荐第一种方式,针对性更强,避免全局设置带来的不必要开销。
验证修改
修改后重新运行程序,到指定时间任务触发时,你应该就能看到所有print的输出了,同时Excel文件也能正常生成,不会再依赖人工输入卡住流程。
内容的提问来源于stack exchange,提问作者Pwizzi
相关产品推荐
相关产品推荐

