[英]How to save AWS CLI command output to var in python?
I am trying to save AWS CLI command into python variable (list).我正在尝试将 AWS CLI 命令保存到 python 变量(列表)中。 The trick is the following code returns result I want but doesn't save it into variable and return empty list.
诀窍是以下代码返回我想要的结果,但不将其保存到变量中并返回空列表。
import os
bashCommand = 'aws s3api list-buckets --query "Buckets[].Name"'
f = [os.system(bashCommand)]
print(f)
output:输出:
[
"bucket1",
"bucket2",
"bucket3"
]
[0]
desired output:所需的输出:
[
"bucket1",
"bucket2",
"bucket3"
]
("bucket1", "bucket2", "bucket3")
If you are using Python and you wish to list buckets, then it would be better to use the AWS SDK for Python, which is boto3
:如果您使用 Python 并且希望列出存储桶,那么最好使用适用于 Python 的 AWS 开发工具包
boto3
:
import boto3
s3 = boto3.resource('s3')
buckets = [bucket.name for bucket in s3.buckets.all()]
See: S3 — Boto 3 Docs请参阅: S3 — Boto 3 文档
This is much more sensible that calling out to the AWS CLI (which itself uses boto!).这比调用 AWS CLI(它本身使用 boto!)要明智得多。
我使用此命令创建所有存储桶的 Python 列表:
bucket_list = eval(subprocess.check_output('aws s3api list-buckets --query "Buckets[].Name"').translate(None, '\r\n '))
You really don't need anything fancy , all you have to do is import subprocess and json and use them :)你真的不需要任何花哨的东西,你所要做的就是导入 subprocess 和 json 并使用它们:)
This was tested using python3.6 and on Linux这是使用 python3.6 和在 Linux 上测试的
output = subprocess.run(["aws", "--region=us-west-2", "s3api", "list-buckets", "--query", "Buckets[].Name"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output_utf8=output.stdout.decode('utf-8')
output_utf8_json = json.loads(output_utf8)
print(output_utf8_json)
for key in output_utf8_json:
print(key)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.