简体   繁体   中英

Print statement not working inside a function when using schedule?

I recently starting learning Python, and am working on a small project for my job. The goal of the program is to connect to & download a dataset from an API at a scheduled time, and then convert the JSON format to a.xlsx file.

In my initial code that just downloaded and converted the data when the script was executed, everything seemed to be working as expected. However, after using schedule to automate the process, the program runs & produces the expected Excel file at the specified time, but does not print any of the statements contained in the api_request function.

I tried removing the scheduled download & reverted just directly calling the function, which restored the expected functionality. Thus, as far as I can tell the issue lies with the schedule expression, but I have so far been unable to find a solution in the schedule documentation.

Any hints or guidance you could provide would be greatly appreciated.

import time
import schedule
import datetime
import requests
import pandas as pd


def api_request(*args):
    print('Initializing API GET request at')
    print(datetime.datetime.now())

    # 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'
                                '&parameters=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)

    # Imports data from the EPA AirNow server
    data_import = response_api.text

    # Prints imported data
    print(data_import)
    print()
    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')
    print(datetime.datetime.now())
    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)

That is because the output is buffered to save system resources. Adding flush=True as an arg in the print will force to flush it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM