使用os.system调用路径名含空格的exe文件
我的代码简单如下:
file = 'C:\\Exe\\First Version\\filename.exe'
os.system(file)
当我运行这个程序时,出现了一个Windows错误:找不到指定的文件。
我发现问题出在“First Version”中间的空格上。我该如何解决这个问题呢?
附注:如果变量'file'被作为参数传递给另一个函数,那该怎么办?
5 个回答
4
试着用双引号把它包起来。
file = '"C:\\Exe\\First Version\\filename.exe"'
os.system(file)
8
我用了这个:
import subprocess, shlex
mycmd='"C:\\Program Files\\7-Zip\\7z" x "D:\\my archive.7z" -o"D:\\extract folder" -aou'
subprocess.run(shlex.split(mycmd))
39
在路径周围加上引号是可以解决问题的:
file = 'C:\\Exe\\First Version\\filename.exe'
os.system('"' + file + '"')
不过更好的办法是使用 subprocess
模块:
import subprocess
file = 'C:\\Exe\\First Version\\filename.exe'
subprocess.call([file])