解决方案 | 如何解决subprocess.Popen(cmd)代码中含有空格路径的问题?

发布时间 2023-05-26 16:00:34作者: IssacNew

 

一、背景

因为在python中需要用到subprocess.Popen(cmd),其中cmd由一堆连接的字符串构成:譬如,xxx.exe inputdir outputdir -arg1 -arg2

(具体例子:1.exe C:\Users\Administrator\Desktop\my output -arg1 -arg2 )

1.exe C:\Users\Administrator\Desktop\新建文件 夹 C:\Users\Administrator\Desktop\my output -arg1 -arg2

但是我的输入输出文件夹中存在空格,需要解决这个问题,网上的一般方法是加上双引号,估计大部分也能通过这个解决问题。对于路径是变量的情况,更好的解决方法在下面!

二、解决方案

中文博客上有不少误导,搜索到这个才是正确的。

 

https://stackoverflow.com/questions/60290732/subprocess-with-a-variable-that-contains-a-whitespace-path

 

为了防止链接失效,把代码复制过来。

 

You can either put double quotes around each argument with potential white spaces in it:

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

or don't use shell=True and instead put arguments in a list:

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

也就是说:在python中把所有参数变为一个变量形成的列表即可。


import subprocess

arg1 = "1.exe" #某个程序(可以是绝对路径)
arg2 =  inputdir #输入路径变量
arg3 = outputdir #输出路径变量
arg4 = "其他参数"
cmd =[arg1, arg2, arg3, arg4]
ps = subprocess.Popen(cmd)
ps.wait()    #让程序阻塞

print("运行结束")