AWS Cloud9中Python S3代码无输出仅返回Process exited with code:0
问题分析与修复方案
核心问题:未启动主逻辑
你的代码定义了main()函数,但没有在代码末尾调用它,程序运行时只会加载模块和函数定义,不会执行任何业务逻辑,所以直接退出,看不到预期的功能菜单。
修复后完整代码(含其他错误修正)
import datetime import logging import boto3 from botocore.exceptions import ClientError def create_bucket(): s3_client = boto3.client("s3") # 注意:S3桶名是全局唯一的,若之前创建过这个桶,需要换个新名字 response = s3_client.create_bucket(Bucket="dylanreed123132") print(response) def delete_bucket(): s3_client = boto3.client("s3") response = s3_client.delete_bucket(Bucket="dylanreed123132") print(response) def upload_object(): s3 = boto3.resource('s3') # Cloud9是Linux环境,不能用Windows路径,建议把文件传到Cloud9工作目录后用相对路径 s3.meta.client.upload_file('./eagleslogo.png', 'dylanreed123132', 'eagleslogo.png') def delete_object(): s3 = boto3.client('s3') # 语法错误:delete.object 改为 delete_object s3.delete_object(Bucket= 'dylanreed123132', Key='eagleslogo.png') def copy_object(): # 拼写错误:resouce 改为 resource s3 = boto3.resource('s3') copy_source = { 'Bucket': 'projectfolder1', 'Key': 'eagleslogo.png' } bucket = s3.Bucket('projectfolder2') bucket.copy(copy_source, 'eagleslogo.png') print('Single file is copied') def download_file(): s3 = boto3.resource('s3') # Cloud9环境用Linux格式路径,比如当前目录的下载文件 s3.Bucket('dylanreed123132').download_file('eagleslogo.png', './downloaded_eagleslogo.png') def main(): s3_handle = boto3.client('s3') while True: print("*** Welcome to the AWS S3 Functionality Console***") print("-Select one of the options below-") print("1. Create a new bucket") print("2. Put object in existing bucket") print("3. Delete object from existing bucket") print("4. Delete bucket") print("5. Copy an object from one bucket to another") print("6. Download an existing object from a bucket") print("7. Exit Program") selection=input("Enter option: ") # 输入是数字,不需要转大写,直接判断即可 if selection == "1": create_bucket() elif selection == "2": upload_object() elif selection == "3": delete_object() elif selection == "4": delete_bucket() elif selection == "5": copy_object() elif selection == "6": download_file() elif selection == "7": print("Goodbye!") now = datetime.datetime.now() print ("Current date and time : ") print (now.strftime("%Y-%m-%d %H:%M:%S")) # 退出循环,结束程序 break # 关键:调用main函数启动程序 if __name__ == "__main__": main()
额外注意事项
- 桶名唯一性:S3桶名是全局唯一的,若之前尝试创建过
dylanreed123132,必须更换未被使用的名称。 - Cloud9路径适配:Cloud9是Linux环境,不能使用Windows的
C:/路径,建议将操作文件上传到Cloud9工作目录,使用相对路径(如./文件名)。 - IAM权限:确保Cloud9环境绑定的IAM角色拥有S3操作权限(如
s3:*或精细的读写权限),否则会触发权限错误。
内容的提问来源于stack exchange,提问作者Dreed66
相关产品推荐
相关产品推荐

