当前位置: 首页 > 知识库问答 >
问题:

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

宰修能
2023-03-14
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

使用初始版本和命令。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. 如果不是,什么是健壮的方法:
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个答案

巫化
2023-03-14
command = split_it('scp {} {}:"{}"'.format(localfile, host, mypath))

>

  • 不是构建命令字符串,而是再次对split_it,直接构建一个参数列表。

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

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

    资料来源/相关岗位:

      null

  •  类似资料:
    • 我试图用curl调用RESTAPI。apiendpoint在程序中动态生成,并上载json文件。 在这里,我正在打印生成的命令,当我从shell运行该命令时,它正在按预期工作。但是,使用Popen运行相同的命令时会抛出一些json验证错误,这是错误的

    • 问题内容: Python版本:2.6.7 我在for循环中有以下subprocess.call,该循环被执行18次,但是,该过程始终挂在第19个循环上: 控制台输出如下所示: 由于我对python脚本不是很熟悉,所以我只是在徘徊我是否在做错什么…我怀疑某个地方出现了死锁。 会处理这些问题吗? 在什么情况下subprocess.call会挂起任何专家答案?非常感谢 问题答案: 当使用子过程时,我倾向

    • 我尝试使用封装签名和javax.xml.crypto.dsig对xml文件进行签名。*班级。结果,我得到了具有正确签名内容但未定义名称空间的文件。如何添加xmlns:ds=”http://www.w3.org/2000/09/xmldsig#“名称空间和相应的ds前缀?我看不到任何地方可以定义它。 示例代码: 给出了示例 XML: 但我想:

    • 问题内容: 我懂了 “无效的列名daysdiff”。 Maxlogtm是日期时间字段。是让我发疯的小东西。 问题答案: 通常,您不能在子句中引用字段别名。(将其视为包括别名在内的全部内容,在该子句之后应用。) 但是,如其他答案所述,您可以强制将SQL视为在子句之前进行处理。通常使用圆括号来强制操作的逻辑顺序,或者使用通用表表达式(CTE)来完成此操作: 括号/子选择: 或参阅亚当的CTE版本答案。

    • #include <stdio.h> #include <stdlib.h> int main(void) { pid_t pid; pid = fork(); if (pid < 0) { exit(1); } else if (pid > 0) { printf("Parent\n");

    • 我想用nodejs打开googlechrome,但我得到了这个错误(我使用了execFile和spawn), 密码