【问题标题】:Running a python script via command in aws lambda在 aws lambda 中通过命令运行 python 脚本
【发布时间】:2023-09-04 04:44:01
【问题描述】:

假设我有一个 python 项目,在我的本地终端中使用命令我可以执行以下操作:

python3 somePythonFile.py --someFlag True --someOtherFlag False -f https://www.somexmlfile/thefile.xml

如果我想在 python Lambda 中运行它,是否可以以相同的方式运行它,而无需作为模块导入。

例如,我试过这个:

import subprocess
from subprocess import Popen

cmd = "python3 somePythonFile.py --someFlag True --someOtherFlag False -f https://www.somexmlfile/thefile.xml"

returned_output = Popen(cmd)

# using decode() function to convert byte string to string
print('Converted result:', returned_output.decode("utf-8"))

但是这给了我一个错误:

[ERROR] FileNotFoundError: [Errno 2] No such file or directory: 'python3 somePythonFile.py --someFlag True --someOtherFlag False -f https://www.somexmlfile/thefile.xml'
Traceback (most recent call last):
  File "/var/task/app.py", line 32, in lambda_handler
    returned_output = Popen(cmd)
  File "/var/lang/lib/python3.8/subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/var/lang/lib/python3.8/subprocess.py", line 1702, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)

【问题讨论】:

    标签: python aws-lambda


    【解决方案1】:

    Popen() 的命令需要将命令行参数分隔在一个列表中。 https://docs.python.org/3/library/subprocess.html#popen-constructor

    换行

    returned_output = Popen(cmd)
    

    到这里

    returned_output = Popen(cmd.split())
    

    就 lambda 而言。我强烈建议您将此代码放在一个模块中(可能会为您节省很多钱)。 AWS Lambda 环境将在处理程序函数返回后立即终止。您需要编写 Lambda 函数代码以等待子流程完成。

    感谢 Mark B 对这个问题的回答 Independent python subprocess from AWS Lambda function

    【讨论】:

    • 谢谢,有没有办法将返回的输出转换为某种字符串?
    • 当然。尝试不同的调用 subprocess.check_output(cmd.split()) docs.python.org/3/library/…
    最近更新 更多