rsync + ssh in the python subprocess gets an error with spaces in the directory name

When I run my Python application (that synchronizes a remote directory locally) I have a problem if the directory that contains my app has one or more spaces in its name. Directory name appears in ssh options like "-o UserKnownHostsFile=<path>" and "-i <path>". I try to double quote paths in my function that generates the command string, but nothing. I also try to replace spaces like this: path.replace(' ', '\\ '), but it doesn't work. Note that my code works with dirnames without spaces. The error returned by ssh is "garbage at the end of line" (code 12) The command line generated seems ok..

rsync -rztv --delete --stats --progress --timeout=900 --size-only --dry-run \
    -e 'ssh -o BatchMode=yes \
    -o UserKnownHostsFile="/cygdrive/C/Users/my.user/my\ app/.ssh/known_hosts" \
    -i "/cygdrive/C/Users/my.user/my\ app/.ssh/id_rsa"'
    [email protected]:/home/user/folder/ "/cygdrive/C/Users/my.user/my\ app/folder/"

What am I doing wrong? Thank you!

Have you tried building your command as a list of arguments - I just had a similar problem passing a key file for the ssh connection:

command = [
  "ssh -o BatchMode=yes -o UserKnownHostsFile='/cygdrive/C/Users/my.user/my\ app/.ssh/known_hosts' -i '/cygdrive/C/Users/my.user/my\ app/.ssh/id_rsa'",
  "[email protected]:/home/user/folder/",
  "/cygdrive/C/Users/my.user/my\ app/folder/"

sp = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = sp.communicate()[0]