Vinay
Vinay

Reputation: 759

How to have a list of possible arguments without hyphens(--) using argparse

I am building a client using Python3. I need to parse arguments sent by the user. Say I have a python script client.py with the following code

    def upload_file(path,compress=False):
        print(path)
        print("uploading")

    def download_file(name):
        print(name)
        print("downloading")

If the script is called with the argument 'upload_file' then upload_file function should be called, and so on...

Here are the various possible ways in which the script can be called.

python client.py upload_file -path /home/user/sample.gz
python client.py upload_file -path /home/user/sample_folder --compress=True
python client download_file -name sample.gz

How do I create a parser using argparse that calls the appropriate function and throws an proper error message when an invalid argument is passed?

Upvotes: 1

Views: 116

Answers (1)

vlemaistre
vlemaistre

Reputation: 3331

Here is an example of how to use a parser with your example :

import os
import argparse


def upload_file(path,compress=False):
    print(path)
    print("uploading")

def download_file(name):
    print(name)
    print("downloading")


def main(argv):
    action = argv.action_to_take
    file = argv.file
    if action == 'download':
        download_file(file)
    elif action == 'upload':
        upload_file(file)
    else:
        print('Action not recognised')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Action to take')
    parser.add_argument('action_to_take', help='input file path on HDFS')
    parser.add_argument('file', help='file to download or upload')
    args = parser.parse_args()
    main(args)

Upvotes: 2

Related Questions