[英]How to run shell commands inside python
I need to create AWS lambda function to execute the python program.我需要创建 AWS lambda function 来执行 python 程序。 I need to incorporate the following shell command in it.我需要在其中合并以下 shell 命令。
curl https://ip-ranges.amazonaws.com/ip-ranges.json | jq -r '.prefixes[] | select(.region=="ap-southeast-1") | .ip_prefix'
Could someone guide me on this.有人可以指导我吗?
To simply shell out to curl and jq to get that data,简单地从 shell 到 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)
but you really probably shouldn't do that since eg there's no guarantee you have curl
and jq
in the Lambda execution environment (not to mention the overhead).但你真的可能不应该这样做,因为例如不能保证你在 Lambda 执行环境中有curl
和jq
(更不用说开销)。
Instead, if you have the requests
library,相反,如果您有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"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.