MHS MHS - 4 years ago 90
Python Question

How to treat whitespace in bash via Python?

I am trying to run the ffmpeg command to record the screen using the

module. Everything is fine with this line:

subprocess.Popen(["ffmpeg", "-video_size", GivenSizeOfScreen, "-framerate", GivenRateOfFrames, "-f", "x11grab", "-i", ":0.0", "-q", GivenQuality, GivenPathAndName])

is something like
. As I said, it's working. (It is in this form because I am getting the folder URI from a GTK widget).

However, the problem is when I select a folder with a white spaces. Like
file:///home/user/Documents/New Folder
. This will give me the following error in terminal:

file:///home/user/Documents/New%20Folder/test.mp4: No such file or directory

I know that this is because of bash misinterpreting the whitespace. And that I can actually run it with putting
before the whitespace to solve it. However, I couldn't manage to find a way to do that from Python sending it to Bash.

Kie Kie
Answer Source

There is nothing about the bash or python in cooperation with the bash. Here is a little example that shows that:

import sys
import os

for arg in sys.argv:  
    print arg

Starting this little script with the bash it'll give you the following:

$ ./ this\ is\ a\ test
this is a test

$ ./ "this is a test"
this is a test

And to be sure about the file://.

$ ./ "file:///test test/"
file:///test test/

So the problem must be with how you get GivenPathAndName from your script or other parts of the program. In order to decode this url encoding use urllib.parse.unquote() for Python3 or urllib.unquote() for Python2.

import urllib
    "-video_size", GivenSizeOfScreen, 
    "-framerate", GivenRateOfFrames, 
    "-f", "x11grab", 
    "-i", ":0.0", 
    "-q", GivenQuality, 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download