Lan*_*nce 6 lambda subprocess popen amazon-web-services python-2.7
我已经成功创建了一个读取和写入 RDS 的 Lambda 函数 (app1)。
我的 Lambda 函数是用 python2.7 编写的,并以压缩包的形式上传。
我在与我的 RDS 和 Lambda 函数相同的 VPC 中的 EC2 实例上创建并测试了压缩包。
接下来,我将功能添加到我的 Lambda 函数,以使用 subprocess.popen 弹出一个独立的子进程 (app2),并让 app1 返回,而 app2 子进程继续独立运行。我测试了 app1 将成功返回其处理程序的输出,而 app2 通过在 app2 中放置 60 秒睡眠并拖尾 app2 的输出文件继续。
我在 EC2 实例中成功测试了 app1 和 app2 功能。
上传新包后,我的 app1 似乎表现得完全符合预期,并立即返回其处理程序的输出,但 app2 功能不会“出现”以实例化,但没有日志、错误或输出可从 app2 捕获。
在 app1 中,我通过在独立的 subproccess.popen 之前和之后执行 subprocess.check_output(['ls','-la']) 来测试该子进程是否工作,并且本地文件夹与我的文件一起显示。除了没有按预期创建的 app2output 文件。
两个问题
应用程序1.py
import subprocess
import sys
import logging
import rds_config
import pymysql
#rds settings
rds_host = "rdshost"
name = rds_config.db_username
password = rds_config.db_password
db_name = rds_config.db_name
port = 3306
logger = logging.getLogger()
logger.setLevel(logging.INFO)
server_address = (rds_host, port)
try:
conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=5)
except:
logger.error("ERROR: Unexpected error: Could not connect to MySql instance.")
sys.exit()
def handler(event, context):
cur = conn.cursor()
isql = "INSERT ..."
cur.execute(isql)
conn.commit()
newid = cur.lastrowid
cur.close()
args = [str(newid),str(event['name'])]
logger.info('ARGS: '+str(args))
print 'pwd: '
output = subprocess.check_output(['pwd'])
print output
print 'ls -la'
output = subprocess.check_output(['ls','-l'])
print output
pid = subprocess.Popen([sys.executable, "app2.py"]+args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
logger.info('PID: '+str(pid))
output = subprocess.check_output(['ls','-l'])
print output
return "{'status':'success','newid':'"+str(newid)+"'}";
Run Code Online (Sandbox Code Playgroud)
app1.py 中“logger.info('PID:'+str(pid))”的输出
就像:“PID:<subprocess.Popen object at 0x7f51aba2a550>”
应用程序2
import sys
import logging
from datetime import datetime
import time
fo = open('app2output','a+')
fo.write("starting with: "+str(sys.argv)+"\n")
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.info("Starting with: "+str(sys.argv)+"\n")
#log accumulated processing time
t1 = datetime.now();
sleep(60)
t2 = datetime.now();
tstring = "{'t1':'"+str(t1)+"','t2':'"+str(t2)+"','args':'"+str(sys.argv[1])+"'}"
logger.info(tstring+"\n")
fo.write(tstring+"\n")
fo.close()
sys.exit()
Run Code Online (Sandbox Code Playgroud)
处理程序函数返回后,AWS Lambda 环境将立即终止。处理程序函数完成后,您无法在 AWS Lambda 环境中的后台运行子进程。您需要对 Lambda 函数进行编码以等待子流程完成。
归档时间: |
|
查看次数: |
6725 次 |
最近记录: |