如何在Python中实现argparse

问题描述 投票:0回答:1

我是Python新手,我弄了一个小脚本来上传文件到S3,目前我只在脚本中硬编码了一个单文件,桶名也是硬编码的。

我想在这个脚本中合并argparse,这样我就可以自己添加一些参数,上传不同的文件。例如,在命令行中,我可以指定参数来决定 file_name x 上传到 bucket_name xxx.

我一直在阅读关于如何设置argparse的文档,但我只能做一些小的改动,不知道如何在我的脚本中用函数来实现它(我猜测 os.rename 将不需要,因为我们会自己解析论证)。) 我知道这些逻辑,只是在实际的代码中很难实现。谁能给我一个例子或者给我一些提示,非常感谢。

python amazon-web-services amazon-s3 command-line-arguments argparse
1个回答
3
投票

下面是脚本在接受命令行参数时的样子。

import argparse
import datetime
import logging
import os
import boto3


def make_new_key(filename: str):
    current_date = datetime.datetime.today().strftime('%Y-%m-%d_%H_%M_%S')
    # The next line handles the case where you are passing the
    # full path to the file as opposed to just the name
    name = os.path.basename(filename)

    parts = name.split('.')
    new_name = f"{parts[0]}{current_date}.csv"
    return new_name

def upload_to_s3(source_filename: str, new_name: str, bucket: str):
    logging.info(f"Uploading to S3 from {source_filename} to {bucket} {key}")
    s3_client = boto3.client("s3")
    with open(source_filename, 'rb') as file:
        response = s3_client.put_object(Body=file,
                                        Bucket=bucket,
                                        Key=new_name,
                                        ACL="bucket-owner-full-control")
        logging.info(response)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--filename')
    parser.add_argument('--bucket')
    args = parser.parse_args()

    new_name = make_new_key(args.filename)
    upload_to_s3(args.filename, new_name, args.bucket)

然后你会像这样调用脚本

python upload.py --filename path/to/file --bucket name_of_bucket
© www.soinside.com 2019 - 2024. All rights reserved.