Python 使用scp复制带空格的文件名文件

0 投票
3 回答
3206 浏览
提问于 2025-04-18 00:25

我正在尝试使用scp在本地网络中复制文件。对于没有空格的文件名,它运行得很好,但一遇到有空格的文件名就崩溃了。我试过把空格替换成"\ ",就像这个例子,但是没有用。以下是我的代码:

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

你可以看看fabric,这是一个Python库,可以简化使用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/')
3

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

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

这样你就不用担心需要转义或加引号的事情了

2

你可以把本地文件 file_pc 保持原样(pipes.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'

撰写回答