Python-如何一次在函数之间发送值

时间:2018-12-10 23:26:07

标签: python function return

所以我试图创建一个脚本,其中有两个函数,第一个函数发送请求并保存两个值,第二个函数将其作为json应用。在继续我的问题之前,我想添加我的代码:

def get_info(thread):


    url = thread #Whatever site such as Google.com

    headers = {
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, br',
        'Pragma': 'no-cache',
        'Cache-Control': 'max-age=0',
    }

    r = requests.get(url, headers=headers, timeout=12)

    bs4 = soup(r.text, "html.parser") #We scrape here


    try:
        search = bs4.find('h1').text
    except:
        search = None

    try:
        image = bs4.find('image')
    except:
        image = None

    #I want to use the search and image on the function below

    --------------------------------------------------------- #Here is where I want to cut

def get_json(): 

    url = thread + '.json' #We just add json at the end to get the website that supports json

    headers = {
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, br',
        'Pragma': 'no-cache',
        'Cache-Control': 'max-age=0',
    }

    r = requests.get(url, headers=headers, timeout=12)

    json_resp = r.json()

    for i in json_resp:
       if search in i['search']: #I use the 'search = bs4.find('h1').text' to match and only want to print if it matches
           print(i)

    try:
        final_name = i['name']
    except:
        final_name = None

    try:
        final_img = i['image']
    except:
        final_img = None

    metadata = {
        'name': final_name,
        'image': final_img

    }
return metadata #return the value

有两个函数get_infoget_json-我要做的是在运行代码时:

while True:
    testing = get_json(thread)
    print(testing)
    time.sleep(5)

输出应为return of get_json-但是我遇到的问题是我只想调用get_json(thread),但要获得get_json(thread)的回报,我需要{em> search 的值仅来自get_info(thread) 一次(始终相同) ,以便能够继续运行 get_json(thread)

我的问题是:如何能在每次致电get_json(thread)时都无需致电get_info(thread)来致电get_json(thread)(获得 search 值仅从get_info(thread)发送一次,每次调用get_json都使用它)

1 个答案:

答案 0 :(得分:1)

如果get_info()的返回值未更改,则可以在进入while循环之前对其进行一次调用,并将get_info()的返回值作为参数与{{1}一起传递给get_json() }