簡體   English   中英

如何停止我的方法在 python 中運行兩次?

[英]How do I stop my method running twice in python?

代碼:

import requests
from time import strftime, sleep

a = 20200422
b = 93

def getData(a,b):
    r = requests.get(
        f"https://www.examplesite.com/docs/doc-{str(a)}-testing-str{b}.pdf")
    if r.status_code == 200:
        with open(f"{b}.pdf", 'wb') as f:
            f.write(r.content)
            print(f"File Saved As {b}.pdf")
            retVal = True
            return retVal  
    else:
        print("[!] File Not Found")
        retVal = False
        return retVal

flag = True
i = 0

while flag:
    i += 1
    if(i == 1):
        retVal = True
    else:
        retVal = getData(a,b)
    if(retVal):
        sleep(2)
        a += 1
        b += 1
        getData(a,b)
    else:
        sleep(10)
        getData(a,b)

output 是:

File Saved As 94.pdf
File Saved As 94.pdf
File Saved As 95.pdf
File Saved As 95.pdf
[!] File Not Found
[!] File Not Found

如果網站上沒有新文件,我怎么做,我不下載它?

當找不到文件時,標志的值仍然是 True。 因此,一個解決方案是:當找不到文件時,將標志設置為 false,因此不會再次調用 getData() function。 `

def getData(a,b):
    r = requests.get(
        f"https://www.examplesite.com/docs/doc-{str(a)}-testing-str{b}.pdf")
    if r.status_code == 200:
        with open(f"{b}.pdf", 'wb') as f:
            f.write(r.content)
            print(f"File Saved As {b}.pdf")
            retVal = True
            return retVal  
    else:
        print("[!] File Not Found")
        retVal = False
        flag= = False
        return retVal

`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM