首页 > 解决方案 > 我将如何在云环境中同时运行两个 python 脚本?

问题描述

我在一个文件中有一个 python 服务器,需要从另一个 python 文件中获取一个 var。问题是,我需要它们在云环境中同时运行。我需要启动第二个,以便它可以通过 API 获取一些数据,然后将其存储在 var 中。然后服务器需要启动,以便它可以启动,获取数据并将其传递给前端。我认为我的语法没问题,但我可以这样做吗?我尝试在本地运行,但一无所获。我可以在云上做到这一点吗?

示例代码

文件 b

import requests

response = ''
def get_data():
        global q
        url = 'apiURL'
        headers = {}
        response = requests.request('GET', url, data='payload', headers=headers)
        q.put(response)

归档一个

from threading import Thread
import helper
import queue

q = queue.Queue()

def start_helper():
        thread_process = Thread(target=helper.get_data)
        thread_process.start()

def get_results():
        global q
        result = q.get()
        return result

start_helper()
print("helper started")
result = get_results()
print("got results")
print(result)
print("ok")

标签: pythonflaskservercloudibm-cloud

解决方案


我想你正在寻找的是线程。线程支持并行处理/执行。假设你有两个 python 文件a.pyb.py,第三个包含你的全局变量,命名为globals.py.

a.py需要从内部进行的 api 调用中获取数据b.py。您可以通过声明调用 api 的函数b.py并在其中的线程中运行它来实现这一点a.py

这是您的示例globals.py文件:

import queue

q = queue.Queue()

这是您在文件中的示例代码b.py

from globals import q

#lots of Python stuff

#function to be called in thread
def my_api_call():
    #some api call made and result stored in a variable named 'result'
    global q
    q.put(result)

#lots of other Python stuff

这是您在文件中的示例代码a.py

from threading import Thread
from globals import q
import b


def start_api_call_in_b():
        thread_process = Thread(target=b.my_api_call)
        thread_process.start()

def get_api_result_from_b():
        result = q.get()
        return result

start_api_call_in_b()
"""
.
.
.
do lots of other stuff
.
.
.
"""
result = get_api_result_from_b()
print(result)

这将导致对' 函数a.py进行线程调用并在全局队列中接收它的结果。b.py当您想接收结果时,只需调用该函数从队列中获取接收到的数据。

还要记住,在函数之外编写的任何代码b.py都将在导入时立即执行。


推荐阅读