简体   繁体   English

如何在 Python 中创建一个无限循环,检查来自请求的变量和局部变量是否不同并触发块

[英]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

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.我正在尝试制作一个 Python 脚本,该脚本作为 NSSM 的后台服务运行,只有在发布新版本的程序时才会执行操作。

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.为此,我想每隔 x 时间检查一次 web URL 请求,并且仅当服务器报告的版本已从本地版本更改时才运行更新程序块。

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.我想将它们放在一个无限循环中,如果 serverversion 和 localversion 相同,它什么也不做,并在重复之前等待一定的时间,如果 serverversion 和 localversion 不同,将触发文件中更高的块。

Put what you have in a while loop, and use the builtin time.sleep把你有的东西放在一个while循环中,并使用内置的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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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