Python scp复制文件,文件名中包含空格

时间:2014-03-29 09:45:11

标签: python filenames space scp

我正在尝试使用scp复制本地网络中的文件。 它适用于没有空格的文件名,但它崩溃了。 我试图将“”替换为“\”作为此exemple,但它不起作用。 这是我的代码:

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 %

如何解决此问题? 感谢

3 个答案:

答案 0 :(得分:2)

使用subprocess模块和/或shlex.split()

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

并且您无需担心转义或引用任何内容

答案 1 :(得分:2)

您可以按原样保留本地文件file_pcpipes.quote将转义空格)。应更改远程文件:

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)

即,user@host:/path/with space应更改为user@host:'/path/with space'

答案 2 :(得分:0)

您可能需要查看fabric,这是一个简化SSH使用的Python库。

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/')