python - 我将如何在云环境中同时运行两个 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")
解决方案
我想你正在寻找的是线程。线程支持并行处理/执行。假设你有两个 python 文件a.py
和b.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
都将在导入时立即执行。
推荐阅读
- spring-data-jpa - Spring Boot DataJpaTest 因 java.lang.IllegalStateException 失败:原因:给定类型必须是接口
- sql - 重复值 SQL
- r - 如何计算R中组内日期的时间间隔?
- python - Python:CERTIFICATE_VERIFY_FAILED,Windows
- angular - 为什么异步管道的新数据不会导致数据重新呈现?
- ios - 存档 Cordova 项目 - 路径不存在:www
- basic - 我可以把整个控制台保存为字符串变量吗?
- python - 如何通过将目录路径作为 Python 中的用户输入将文档(即 .docx 文件)转换为 Python 中的 .pdf?
- android - 当服务器禁用 TLS 1.0 和 1.1 时,即使是最新版本的 Android 应用程序也会崩溃
- javascript - JavaScript if 和 else if 语句无法正常工作