如何在 Python 中实现 argparse [英] How to implement argparse in Python

查看:30
本文介绍了如何在 Python 中实现 argparse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to Python, I got a small script to upload files to S3, at the moment I only hard-code one single file in the script, the bucket name is also hard-coded.

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

I wanted to merge argparse in this script so that I can add some arguements by myself and upload different files. For example, in the command line I can specify arguments to decide file_name x upload to bucket_name xxx.

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

I've been reading documents about how to set argparse but I can only make small changes and don't know how to implement it with the function in my script (I guess os.rename will be unnecessary because we'll parse the arguements by ourselves). I know the logic, just having difficulty to implement them in the actual code... Can someone gave me an example or gave me some hint, many thanks.

推荐答案

这里是脚本接收命令行参数的样子.

Here is how the script would look taking command line arguments.

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)

然后你会像这样调用脚本

Then you would call the script like this

python upload.py --filename path/to/file --bucket name_of_bucket

这篇关于如何在 Python 中实现 argparse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆