【问题标题】:How to run shell commands inside python如何在python中运行shell命令
【发布时间】:2021-08-30 04:05:37
【问题描述】:

我需要创建 AWS lambda 函数来执行 python 程序。 我需要在其中加入以下 shell 命令。

curl https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[] | select(.region=="ap-southeast-1") | .ip_prefix'

有人可以指导我吗?

【问题讨论】:

标签: python python-3.x python-2.7


【解决方案1】:

为了简单地使用 curl 和 jq 来获取数据,

import subprocess

data = subprocess.check_output("""curl https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[] | select(.region=="ap-southeast-1") | .ip_prefix'""", shell=True)

但你真的可能不应该这样做,因为例如无法保证您在 Lambda 执行环境中拥有 curljq(更不用说开销了)。

相反,如果您有 requests 库,

import requests

resp = requests.get("https://ip-ranges.amazonaws.com/ip-ranges.json")
resp.raise_for_status()
prefixes = {
    r["ip_prefix"]
    for r in resp.json()["prefixes"]
    if r["region"] == "ap-southeast-1"
}

【讨论】:

  • 非常感谢。他们是我将所有 IP 存储在一个文件中的一种方式吗
  • 一般来说是的,当然你可以把它们写到一个文件中。但是,您不能在 lambda 函数中写入文件。
  • 明白。我需要获取这些输出 IP 并将它们存储在一个文件中,然后将文件转储到 S3 以进行进一步处理。
  • 所以你需要将它们存储在 S3 中吗?很好,你可以做到; boto3 库是 Python 的首选 S3 客户端。