如何在 python 中 运行 shell 命令

How to run shell commands inside python

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

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

有人可以指导我吗。

只需 shell out 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"
}