Skip to content

CLI Script Conventions

Giselle Martel edited this page Jan 22, 2021 · 3 revisions

CLI scripts are located in ivadomed/scripts. Each script is a tool built on top of the submodules within the ivadomed Python package. (For example, ivadomed/scripts/download_data.py is a command-line tool for downloading various datasets to train ivadomed models.)

Ivadomed scripts can be called from the terminal: ivadomed_{your_script_file_name (e.g. ivadomed_download_data)

Each CLI script follows a specific structure, and must contain the following components:

  1. Setup, description, and attribution
  2. Imports
  3. if __name__ == "__main__" block
  4. main() function
  5. get_parser(): Argparse conventions

1. Setup, description, and attribution

At the very top of the file, we use a commented section to describe the script and provide attribution.

#!/usr/bin/env python
"""
This script ... <DESCRIPTION HERE>

Usage: <HOW TO CALL THE SCRIPT>

Contributors: <CONTRIBUTOR NAME>
"""

2. Imports

Imports should be grouped by type into one of 3 categories. Each import should also be a separate line.

# Standard library imports
import os
import sys
import argparse

# Third party imports
import numpy as np
import pandas as pd

# Location application/library specific imports
from ivadomed import utils as imed_utils

For standard libraries, DO NOT use, for example, from package import function (because of redundant cyclic import in python call). Instead, use import package or import package as pkg, then use pkg.path in code.

3. if __name__ == "__main__" block

This is located at the very bottom of the file, and should stay minimal, as follows:

if __name__ == '__main__':
    main()

4. main() function

def main(args=None):
    imed_utils.init_ivadomed()
    parser = get_parser()
    args = imed_utils.get_arguments(parser, args)

5. get_parser()

get_parser() is a function used to set up an ArgumentParser object for parsing CLI arguments. Please refer to the conventions below when setting up your parser:

Argparse initialization example:

    parser = argparse.ArgumentParser(
        description="Prepare data",
        formatter_class=SmartFormatter,
        add_help=None,
        prog=os.path.basename(__file__).strip(".py")
    )