[Tutor] Using subprocess on a series of files with spaces

Cameron Simpson cs at zip.com.au
Fri Aug 1 03:42:50 CEST 2014


On 01Aug2014 08:35, Steven D'Aprano <steve at pearwood.info> wrote:
[...]
>> I want to use Python to call ffmpeg to convert each file to an .mp3.
>> So far this is what I was trying to use:
>> import os, subprocess
>> track = 1
>> for filename in os.listdir('myDir'):
>>     subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3'])
>>     track += 1

This is basicly ok, except that as others have mentioned you need to put 
"myDir/" on the front of filename, because the file is in the subdirectory.  
probably also with the mp3 output filename depending what you intend.

>I believe that your problem is *not* the spaces, but that you're passing
>just the filename and not the directory. subprocess will escape the
>spaces for you.

I wish people would not say this. subprocess DOES NOT escape the spaces, nor 
does it need to.

The only reason the OP imagines he needs to escape spaces it that he is 
probably testing his ffmpeg command in a shell (entirely reasonable). And in a 
shell you need to escape the spaces to prevent the shell deciding that they are 
separating words. An entirely syntactic issue.

However, the subprocess call above uses a list for the command, and that form 
DOES NOT pass anything to the shell. The command gets executed directly. And 
therefore no spaces need escaping at all.

Just getting this out before we further confuse the OP.

Cheers,
Cameron Simpson <cs at zip.com.au>


More information about the Tutor mailing list