Search code examples
pythonpython-3.xffmpeg

How to use python variable inside ffmpeg command


I've python variable like this

diff #var


print(diff)
output: 0:01:36.992727

print(type(diff))
output: <class 'datetime.timedelta'>

I want to use this dif var inside ffmpeg command

os.system(' ffmpeg -i Thermal.mkv -ss 00:00:01 -t $diff -async 1 -c copy cut.mp4 ')

error I'm getting

Invalid duration specification for t: diff

I also tried

os.system(' ffmpeg -i Thermal.mkv -ss 00:00:01 -t "$diff" -async 1 -c copy cut.mp4 ')

also

os.system(' ffmpeg -i Thermal.mkv -ss 00:00:01 -t "${diff}" -async 1 -c copy cut.mp4 ')

when I given directly it works...

os.system(' ffmpeg -i Thermal.mkv -ss 00:00:01 -t  0:01:36.992727 -async 1 -c copy cut.mp4 ')

Am i missing anything here?...It's not the right way to do it?. If you guys know any reference pls share with me


Solution

  • You try to use bash-styled variable injection to string, however you need to inject variable to string on python level, and then run os.system() on this string.

    Use f-strings literal interpolation like this:

    cmd = f'ffmpeg -i Thermal.mkv -ss 00:00:01 -t {diff} -async 1 -c copy cut.mp4'
    

    Another part is preparing your diff variable. I assume ffmpeg expects duration in seconds, so you have to convert your datetime.timedelta to seconds

    diff # some var
    print(diff) # 0:01:36.992727
    print(type(diff)) # <class 'datetime.timedelta'>
    diff = int(diff.total_seconds())
    cmd = f'ffmpeg -i Thermal.mkv -ss 00:00:01 -t {diff} -async 1 -c copy cut.mp4'
    os.system(cmd)