简体   繁体   中英

How to Make a CLI for a Git Repository Using Python Argparse and Click

I am trying to make a CLI tool to execute python scripts within the repository. A friend of mine has been helping me out, but considering this is my first time at using argparse and click to make a CLI, I am having issues in executing it properly. My goal is to make a CLI that will work with all of my sub-directories within my Python Folder:

https://github.com/Richard-Barrett/SalesforceCLI/tree/master/Python

Once here, I have a script in there called: sfdc.py that I would like to eventually import as a path in /usr/local/bin to execute within a shell.

The main script that accomplishes this should be sfdc.py and I want to call it like this

python sfdc.py <sub-directory> <optional_flag> so that the sub-directory is an argument and the executable script is an optional flag.

Here is the main code: https://github.com/Richard-Barrett/SalesforceCLI/blob/master/Python/sfdc.py

Actual Code:

#!/usr/bin/env python
import argparse

parser = argparse.ArgumentParser(
    description='SalesforceCLI will return Pandas Dataframes from Salesforce Cases within an Organizations SFDC. It will also allow you to interact with Salesforce Lighting Experience or Service console from within the CLI. You will even be able to make leads, create cases, and send off emails all from your CLI!',
    epilog="SalesforceCLI is here to help you automate reports and data within your Organizations SFDC"
)

# Poitional Arguments
parser.add_argument('accounts', help='Pandas Dataframe that shows all available accounts active within an organizational SFDC')
parser.add_argument('cases', help='cases dataframes related to defined case report, default is set to all cases')
parser.add_argument('contacts', help='return a list of contacts as a dataframe')
parser.add_argument('leads', help='leads dataframes related to all defined leads for user access, default is set to all concurrent leads within an organizational SFDC')
parser.add_argument('lightning', help='Work with Salesforce Lightning from the CLI')
parser.add_argument('service', help='Work with Salesforce Service Console from the CLI')
parser.add_argument('soql', help='SOQL custom query for users within an SFDC')
parser.add_argument('reports', help='reports dataframes related to defined reporst, default is set to list all available reports for use with SFDC access')

# Optional Arguments
parser.add_argument('-v','--version', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='Returns the version of SalesforceCLI'),
#printf("Optional Arguments for cases")
parser.add_argument('-s1','--sev1', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='Return Pandas Dataframe for all Severity Level 1 Cases')
parser.add_argument('-s2','--sev2', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='Return Pandas Dataframe for all Severity Level 2 Cases')
parser.add_argument('-s3','--sev3', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='Return Pandas Dataframe for all Severity Level 3 Cases')
parser.add_argument('-s4','--sev4', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='Return Pandas Dataframe for all Severity Level 4 Cases')

args = parser.parse_args()

if args.sev1:
   execfile('Cases/read_all_sev1_cases.py')

if args.sev2:
   execfile('Cases/read_all_sev2_cases.py')

How can I make a CLI tool using this structure? The help and text output are almost to what I want. I even changed it to include lines like this, but it has not worked.

parser.add_argument('-s2','--sev2', action='store_true',
                    help='Return Pandas Dataframe for all Severity Level 2 Cases')

Does anyone have any suggestions on how to write a CLI for using python?

I am trying to run the code in a manner of

python sfdc.py cases --sev2

When I run it I get the following traceback:

 richardbarret@1152-MBP  ~/Git/SalesforceCLI/Python   master ● ⍟1  python sfdc.py cases -s1                                                             ✔  1128  20:19:53
usage: sfdc.py [-h] [-v] [-s1]
               accounts cases contacts leads lightning service soql reports
sfdc.py: error: too few arguments

So, using Click , since it's tagged in the question, what I have ended up with to implement this is the following:

import click


def sev1():
    os.system('python3 ~/Git/SalesforceCLI/Python/Cases/read_all_sev1_cases.py')

def sev2():
    os.system('python3 ~/Git/SalesforceCLI/Python/Cases/read_all_sev2_cases.py')

def sev3():
    os.system('python3 ~/Git/SalesforceCLI/Python/Cases/read_all_sev3_cases.py')

def sev4():
    os.system('python3 ~/Git/SalesforceCLI/Python/Cases/read_all_sev4_cases.py')

def handover():
    os.system('python3 ~/Git/SalesforceCLI/Python/Cases/read_all_handover_cases.py')

severities = [sev1, sev2, sev3, sev4]

@click.command('sfdc')
@click.argument('subdirectory', type=click.Path())
@click.version_option()
@click.option('-ho', '--handover', 'do_handover', is_flag=True)
@click.option('-s', '--severity', type=click.Choice(['1', '2', '3', '4']), required=False)
def sfdc(subdirectory, do_handover, severity):
    subdirectory = os.path.abspath(subdirectory)
    if severity:
        severity = int(severity) - 1
        severity_method = severities[severity]
        severity_method()
    if do_handover:
        handover()


if __name__ == '__main__':
    sfdc()

This seems to tick off all requirements and is, in my opinion at least, slightly more readable. Does this help solve your issue?

An example execution is:

python sfdc.py -ho -s 1
python sfdc.py -ho
python sfdc.py -s 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM