Jerry Gao
Jerry Gao

Reputation: 1439

python argparse with time format

i have a script which take hh:mm:ss inputs

for example

vid_cut.py -t 00:00:30 00:10:00

but when i do

from sys import argv
from argparse import ArgumentParser as AP

ap = AP()
ap.add_argument('-f',type=str)
ap.add_argument('-tp',nargs='+',type=str)

arg = ap.parse_args(argv)

print arg['-tp']

i got

vid_cut.py: error: unrecognized arguments: vid_cut.py

how can I make argparse understand my inputs?

updates

I have now solved the problem, with the following code

# imports
from os import system as sc
from sys import argv
from argparse import ArgumentParser as AP
from itertools import tee , izip



# cmd synthesis
ap = AP()
ap.add_argument('-f',type=str)
#ap.add_argument('-tp',nargs='+',type=str)
ap.add_argument('-tp',nargs='+',type=str)

arg = vars(ap.parse_args())

print argv
print arg
f_name = arg['f']
tp = map(HMS_S, arg['tp'])

ffmpeg_cmd = "ffmpeg -sameq -ss %s -t %s -i %s %s"

# system call 

for t,dt in diff(tp):
    print ffmpeg_cmd % (t,dt,f_name,f_name + str(t))

the only question is I don't know why when do we need to do arg = vars(ap.parse_args(something))

it seems argv has been magically processed.

answer: argv[1:] will be automatically processed, unless you have other stuff to parse.

Upvotes: 0

Views: 881

Answers (2)

Morten Kristensen
Morten Kristensen

Reputation: 7623

Since you haven't given very much code I'll show an example that will work:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-t', nargs='+', type=str)

# If no argument is given to parse_args() then the argument strings of
# the program are taken from sys.argv. And be sure not to pass in
# sys.argv[0] if you specify them instead supply sys.argv[1:].
args = parser.parse_args()

print(args.t)

If run with "-t 00:00:30 00:10:00" as arguments then I get this value back:

['00:00:30', '00:10:00']

Upvotes: 3

ᅠᅠᅠ
ᅠᅠᅠ

Reputation: 67030

Without more code it's hard to know what's wrong, but you may be passing all of sys.argv to parse_args(). You should pass sys.argv[1:], i.e. only the arguments, not the program name.

Upvotes: 1

Related Questions