如何在本地Python腳本中運行AWS cli命令?

2024-04-29 08:38:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试运行这个aws s3 ls命令:

aws s3 ls s3://path/to/my/bucket/12434 --recursive --human-readable --summarize

用这条Python:

command = 'aws s3 ls s3://path/to/my/bucket/12434 --recursive --human-readable --summarize'
s3_folder_data  = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
print s3_folder_data

但它失败了,出现了这个错误:

subprocess.CalledProcessError: Command 'aws s3 ls s3://path/to/my/bucket/12434 --recursive --human-readable --summarize' returned non-zero exit status 1

当我运行这个命令时,它本身就工作了。同一台计算机上的同一用户正在调用python脚本。给什么?


Tags: topath命令awss3bucketmyfolder
2条回答

Python 3.5的新特性,您还可以使用^{}

subprocess.run(['aws', 's3', 'ls', 's3://path/to/my/bucket/12434', '--recursive', '--human-readable', '--summarize'])

正如其他人所建议的,使用Boto3 S3库来获得您想要的。但如果你坚持要subprocess,请尝试:

subprocess.check_output(['aws', 's3', 'ls', 's3://path/to/my/bucket/12434', '--recursive', '--human-readable', '--summarize'])

或者

subprocess.call(['aws', 's3', 'ls', 's3://path/to/my/bucket/12434', '--recursive', '--human-readable', '--summarize'])

并以此为基础。

相关问题 更多 >