调用子进程时在文件名中引用空格

时间:2017-06-16 18:52:47

标签: python shell subprocess scp spaces

有人提出了在文件名中放置空格的好主意。我需要使用该文件名从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"']
  1. 有没有现成的解决方案?
  2. 如果没有,那么强有力的做法是什么:
  3. 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"']
    

1 个答案:

答案 0 :(得分:4)

command = split_it('scp {} {}:"{}"'.format(localfile, host, mypath))
  1. 不是再建立一个命令字符串,而是再次split_it,而是直接建立一个参数列表。

  2. 为了向远程文件路径添加一层引用,请使用shlex.quote(如果使用较旧的Python版本,则使用pipes.quote。)

  3. command = ['scp', localfile, '{}:{}'.format(host, shlex.quote(mypath))]
    

    来源/相关帖子: