简体   繁体   English

如何在 python 中运行 shell 命令

[英]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 执行环境中有curljq (更不用说开销)。

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.

相关问题 如何启动Python ipython shell,在其中自动运行一些命令,并保持打开状态? - How to start a Python ipython shell, automatically run inside it a few commands, and leave it open? 如何使用python打开adb shell并在shell中执行命令 - How to open adb shell and execute commands inside shell using python 如何在Python脚本中运行bash命令 - How to run bash commands inside of a Python script 如何从 Python 运行云 shell 命令? - How can I run cloud shell commands from Python? 如何使用Python在同一个TCL shell上运行命令 - How to run commands on same TCL shell using Python 如何实现线程化以在python中运行两个bash shell命令? - How to implement threading to run two bash shell commands in python? 如何使用python subprocess命令在不同目录中运行shell命令? - How to run shell commands in different directory using python subprocess command? 如何使用Python脚本在Shell / Linux中运行sudo命令 - How to run sudo commands in shell/linux using python script 如何在IPython中运行shell命令? (Python分析GUI工具) - How to run shell-commands in IPython? (Python Profiling GUI tools) 如何在Windows的终端中运行python shell? - How to run the python shell inside a terminal in Windows?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM