Slice notation with command line options

Output result

$ python untitled.py -sl 100:200,:,:5
(500, 500, 10)
(100, 500, 5)
$ python untitled.py -sl :,100:300:10,4
(500, 500, 10)
(500, 20)

Below is the source. Maybe there is another good way to write

import argparse
import numpy as np

def parse2slice(snapshot):

    def parsesection(snap):
        try:
            section = int(snap)
        except ValueError:
            section = [int(s) if s else None for s in snap.split(':')]
            if len(section) > 3:
                raise ValueError('snapshots input incorrect')
            section = slice(*section)
        return section

    section = [s if s else None for s in snapshot.split(',')] 
    return tuple([parsesection(section[i]) for i in range(len(section))])

parser = argparse.ArgumentParser()
parser.add_argument('-sl', '--slice', type=str,  required=False)
args = parser.parse_args()


arr = np.array([[[0 for k in range(10)] for i in range(500)] for j in range(500)])
print arr.shape
print arr[(parse2slice(args.slice))].shape

Recommended Posts

Slice notation with command line options
ls command options
Command line introductory notes
Linux command line shortcut
Use Python 3 introduced with command line tools on macOS Catalina
Frequently used ps command options
Twitter post from command line
Encryption / decryption with GPG command
MyCLI: Command line interface with auto-completion for MySQL, MariaDB and Percona