【发布时间】:2017-11-19 15:19:07
【问题描述】:
有人想出了在文件名中放置空格的绝妙主意。我需要使用该文件名从 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(" ")的naive版本:
['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"']
【问题讨论】:
-
相关,虽然不是直接重复:stackoverflow.com/questions/19858176/…
-
@mkrieger1:链接中的引用正是我在开始时创建 scp 命令的方式。之后麻烦就开始了。
-
是的,正如那里的最佳答案所述,您需要以某种方式双重转义空格。但我不确定在 Python 中是否有很好的方法来做到这一点。
-
即
command = ['scp', localfile, '{}:{}'.format(host, shlex.quote(mypath))] -
@delavnog, any 参数最终会作为数组元素传递给您正在运行的程序(请记住,
int main(int argc, char** argv)是 any 调用新可执行文件时的任何情况,无论它是用什么语言实现的)。你为什么要创建一个可以正确分割成数组的格式的字符串,而不是一开始就指定你真正想要的字符串数组?
标签: python shell subprocess scp spaces