如何在 Python 中实现 argparse

How to implement argparse in Python

我是 Python 的新手,我有一个将文件上传到 S3 的小脚本,目前我只在脚本中硬编码一个文件,存储桶名称也是硬编码的.

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

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

这是脚本接受命令行参数的样子。

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