Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite input using argparse

So say I have a merge function. I can merge any number of files into one. This requires a variable number of inputs. So my question is, taking in arguments from argparser, how would I account for the possibility of 2 or more input files?


1 Answers

You can use either nargs='+' or nargs='*'.
These will gather the args into a list.

import argparse
the_parser = argparse.ArgumentParser()
the_parser.add_argument('--input_files',nargs='+')
args = the_parser.parse_args()

If you want to call from another script using subprocess you could do:

import subprocess
the_files = ['to_merge_1.txt', 'to_merge_2.txt']
cmdlnargs = ['python','argparse_example.py','--input_files']
cmdlnargs.extend(the_files)

subp = subprocess.Popen(cmdlnargs,
                        stdout=subprocess.PIPE, 
                        stdin=subprocess.PIPE,
                        stderr=subprocess.STDOUT)    
stdout, stderr = subp.communicate()
print stdout
like image 72
mechanical_meat Avatar answered Mar 31 '26 06:03

mechanical_meat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!