Python scp copy file with spaces in filename

2019-03-04 04:13发布

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

3条回答
啃猪蹄的小仙女
2楼-- · 2019-03-04 04:44

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楼-- · 2019-03-04 04:47

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/')
查看更多
贼婆χ
4楼-- · 2019-03-04 04:55

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'

查看更多
登录 后发表回答