Python scp copy file with spaces in filename

2019-03-04 04:18发布

问题:

I'm trying to copy files in local network with scp. It's working well with filenames without spaces, but it crash with. I've tried to replace " " with "\ " as this exemple, but it don't work. Here is my code:

def connection(locals):
         a = (int(re.search(br'(\d+)%$', locals['child'].after).group(1)))
         print a
         perc = (Decimal(a)/100)
         print (type(perc)), perc
         while gtk.events_pending():
             gtk.main_iteration()
         FileCopy.pbar.set_text("Copy of the file in the Pi...   " + str(a) + "%")
         while gtk.events_pending():
             gtk.main_iteration()
         FileCopy.pbar.set_fraction(perc)

file_pc = "/home/guillaume/folder/a very large name of file with space .smthg"
file_pi = "pi@192.168.X.X:/home/pi/folder/a very large name of file with space .smthg"

if " " in file_pc:
   file_pc = fichier_pc.replace(" ", '\\\ ')   # tried '\\ ' or '\ '
   file_pi = fichier_pi.replace(" ", '\\\ ')   # but no way
else:
   pass
command = "scp %s %s" % tuple(map(pipes.quote, [file_pc, file_pi]))
pexpect.run(command, events={r'\d+%': connection}) # this command is using to get the %

How can I fix this problem ? Thanks

回答1:

You may keep local file file_pc as is (pipes.quote will escape the spaces). The remote file should be changed:

import pipes

file_pi = 'pi@192.168.X.X:/home/pi/folder/file with space.smth'
host, colon, path = file_pi.partition(':')
assert colon
file_pi = host + colon + pipes.quote(path)

i.e., user@host:/path/with space should be changed to user@host:'/path/with space'



回答2:

Use subprocess module and/or shlex.split():

import subprocess
subprocess.call(['scp', file_pc, file_pi])

and you don't need to worry about escaping or quoting anything



回答3:

You might want to look into fabric, a Python library that streamlines the use of SSH.

from fabric.state import env
from fabric.operations import get

env.user = 'username'
env.key_filename = '/path/to/ssh-key'

get('/remote_path/*', 'local_path/')