【问题标题】:Subprocess with a variable that contains a whitespace (path)具有包含空格(路径)的变量的子进程
【发布时间】:2020-02-19 08:04:06
【问题描述】:

刚刚再次启动 Python,现在我已经陷入了以下困境......

我正在尝试将 subprocess.Popen 与一个带有空格的变量一起使用(Windows 路径)。

对变量进行打印,该变量似乎工作正常。但是在subprocess.Popen中使用变量时,变量会被第一个空格截断。

在脚本的一部分下方(变量“image_file”包含带有空格的 Windows 路径)

def start_phone(image_file):
    cmd = tar_exe + " -tf "+ image_file
    print (cmd)
    subprocess.Popen(cmd, shell=True)

如何使用带有空格(路径)的变量的子进程?

【问题讨论】:

    标签: python subprocess removing-whitespace


    【解决方案1】:

    您可以在每个带有潜在空格的参数周围加上双引号:

    cmd = f'"{tar_exe}" -tf "{image_file}"'
    subprocess.Popen(cmd, shell=True)
    

    或者不要使用shell=True,而是将参数放在一个列表中:

    subprocess.Popen([tar_exe, '-tf', image_file])
    

    【讨论】:

      【解决方案2】:

      如果您查看subprocess documentation,您会发现参数必须以列表的形式提供给子进程命令,因此您的代码示例应如下所示

      def start_phone(image_file):
          subprocess.Popen([tar_exe, "-tf", image_file])
      

      【讨论】:

        猜你喜欢
        • 2011-05-19
        • 2022-12-05
        • 1970-01-01
        • 1970-01-01
        • 2012-02-26
        • 1970-01-01
        • 1970-01-01
        • 2013-07-07
        • 2013-04-07
        相关资源
        最近更新 更多