有人提出了在文件名中放置空格的好主意。我需要使用该文件名从python执行scp,这是有问题的,因为shell解析命令,而scp也有一些关于空格的怪癖。这是我的测试代码:
import subprocess
import shlex
def split_it(command):
return shlex.split(command)
#return command.split(" ")
def upload_file(localfile, host, mypath):
command = split_it('scp {} {}:"{}"'.format(localfile, host, mypath))
print(command)
res = subprocess.run(command, stdout=subprocess.PIPE)
return res.stdout.decode()
upload_file("localfile.txt", "hostname", "/some/directory/a file with spaces.txt")
给出了:
['scp', 'localfile.txt', 'hostname:/some/directory/a file with spaces.txt']
scp: ambiguous target
将朴素版本与command.split(" ")
:
['scp', 'localfile.txt', 'hostname:"/some/directory/a', 'file', 'with', 'spaces.txt"']
spaces.txt": No such file or directory
正确的工作scp命令是:
['scp', 'localfile.txt', 'hostname:"/some/directory/a file with spaces.txt"']
split_it('scp localfile.txt hostname:"/some/directory/a file with spaces.txt"')
# returns ['scp', 'localfile.txt', 'hostname:"/some/directory/a file with spaces.txt"']
答案 0 :(得分:4)
command = split_it('scp {} {}:"{}"'.format(localfile, host, mypath))
不是再建立一个命令字符串,而是再次split_it
,而是直接建立一个参数列表。
为了向远程文件路径添加一层引用,请使用shlex.quote
(如果使用较旧的Python版本,则使用pipes.quote
。)
command = ['scp', localfile, '{}:{}'.format(host, shlex.quote(mypath))]
来源/相关帖子: