treetop treetop - 4 years ago 130
Linux Question

Python3 - Inserting the value of a variable into another variables command

I'm creating a basic transcoder in Python3, but this question is not about transcoding, more about variables within commands, hence the reason I'm only including the information that is necessary.
This line extracts the text from the combobox/dropdown menu and can either be 400k 700k or 1500k:

vbit = str(self.ui.comboBox1.currentText())

^ This bit works fine.
I have this bit of code which is capable of passing an argument to ffmpeg and transcoding a file.

cmd = '-i "%s" -vcodec libx264 -crf 23 -b:v 400k -b:a 260k "%s.mp4"'

^ this work when I write the value as 400k within the code, so again there are no issues with this bit.

Here is my issue- I want the value of
to be inserted into the command above where the 400k is, depending on what value is contained within vbit (i.e. 400k, 700k or 1500k). I'm trying to insert the value of vbit into the line. I've tried this but its not working.

cmd = '-i "%s" -vcodec libx264 -crf 23 -b:v " + vbit + " -b:a 260k "%s.mp4"'

This is a question essentially about the right syntax for inserting a variable into a line of code.

Answer Source

Either open and close your string literals appropriately:

vbit = '400k'
cmd = '-i "%s" -vcodec libx264 -crf 23 -b:v ' + str(vbit) + ' -b:a 260k "%s.mp4"'
#  '-i "%s" -vcodec libx264 -crf 23 -b:v 400 -b:a 260k "%s.mp4"'

or use string formatting:

vbit = '400k'
cmd = '-i "%s" -vcodec libx264 -crf 23 -b:v {} -b:a 260k "%s.mp4"'.format(vbit)
#  '-i "%s" -vcodec libx264 -crf 23 -b:v 400 -b:a 260k "%s.mp4"'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download