TheChymera
TheChymera

Reputation: 17934

Pass bash file list to python CLI function

I am using python's argparse to create command line bindings for popular functions from my software. More specifically I am talking about this function.

Usually when I want a CLI function to take a list of inputs in bash, I can do something like:

whateverfunction DSC_4{322..399}*

which will pass the function all values from DSC_4322 to DSC_4399 with whatever suffixes. Now, obvioulsy, this will not work if I am just passing a sting with argparse meaning to crawl the path in python:

parser.add_argument("destination", help="Path to store files into (excluding alphanumeric storage directories)", type=str)

Is there any elegant way to allow an argparse positional argument to handle bot a path and a list of files?

The only thing I could think of is detecting the accolades in the string and writing a python script which generates a list for such an input - and performs a tree crawl for any other kind of input... But I was hoping there might be a nicer way.

Upvotes: 0

Views: 384

Answers (1)

hpaulj
hpaulj

Reputation: 231415

So with a simple script that echos the sys.argv

1959:~/mypy$ python echoargv.py stack{342..344}*
['echoargv.py', 'stack34234965.py', 'stack34279750.py', 'stack34308904.py', 'stack34432056.py']

I get a list of filenames

parser.add_argument("filenames", nargs='*')

will produce an args namespace like:

Namepace(filenames=['echoargv.py', 'stack34234965.py', 'stack34279750.py', 'stack34308904.py', 'stack34432056.py'])

Where there's no match I get a list like

python echoargv.py stack{23..24}*
['echoargv.py', 'stack23*', 'stack24*']

If you want generate a list of files from within the Python script, consider using glob.glob.

In [137]: glob.glob('stack342*')
Out[137]: ['stack34234965.py', 'stack34279750.py']

(though it does not, apparently, implement the {..} syntax.)

Upvotes: 2

Related Questions