
The problem.
ffmpeg allows multiple inputs to be specified using the same keyword, like this:
ffmpeg -i input1.mp4 -i input2.webm -i input3.mp4
Let’s say you are trying to write a script in python that accepts multiple input sources and does something with each one, as follows:
python_script -i input1.mp4 -i input2.webm -I input3.mp4
How do we do this in argparse?
Using argparse, you are facing an issue as each option flag can only be used once. You know how to associate multiple arguments with a single option (using nargs=’*’ or nargs=’+’), but that still won’t allow you to use the -i flag multiple times.
How can this be accomplished?
Here’s a sample code to accomplish what you need using argparse library
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', action='append', type=str, help='input file name')
args = parser.parse_args()
inputs = args.input
# Process each input
for input in inputs:
# Do something with the input
print(f'Processing input: {input}')
With this code, the input can be passed as:
python_script.py -i input1.mp4 -i input2.webm -i input3.mp4
The key in the whole program is the phase “append” in the action keyword.
Hope this helps.
Learn more