How do I create an Infinite Loop in Python that checks if a variable from a request and a local variable are different and trigger a block

Viewed 19

I am trying to make a Python script that runs as a background service with NSSM that will only preform an action when a new version of a program is released.

To do this I want to check a web URL with requests every x amount of time and only if the version the server reports has changed from the local version run a updater block.

I currently have the block that does the update working fine but I just don't know how I would compare the request result and local version info from a file and only run that block if they don't match.

I get the newest version on the server with this code:

winclientsettings = requests.get('https://myapi.website/client-version/Windows')
winclientdict = winclientsettings.json()
serverversion = list(winclientdict.values())[1]

And the local version with:

appdata = os.getenv('LOCALAPPDATA')
programfolder = appdata + '/My Program'
versionfile = programfolder + '/localversion'
with open(versionfile, "r") as file:
    localversion = file.readline()

I want to put these together into an infinite loop, where if serverversion and localversion are the same it just does nothing and waits a set amount of time before repeating, and if serverversion and localversion are different, will trigger a block higher in the file.

1 Answers

Put what you have in a while loop, and use the builtin time.sleep

import os
import time

import requests

WAIT_SECONDS = 300

appdata = os.getenv('LOCALAPPDATA')
programfolder = appdata + '/My Program'
versionfile = programfolder + '/localversion'


def get_server_version():
    winclientsettings = requests.get(
        'https://myapi.website/client-version/Windows')
    winclientdict = winclientsettings.json()
    serverversion = list(winclientdict.values())[1]
    return serverversion


def get_local_version():
    with open(versionfile, "r") as file:
        localversion = file.readline()
    return localversion


def update_if_new():
    server_version = get_server_version()
    local_version = get_local_version()
    if server_version != local_version:
        with open(versionfile, "w") as file:
            file.write(server_version)


def main():
    while True:
        update_if_new()
        time.sleep(WAIT_SECONDS)


if __name__ == '__main__':
    main()

Related