路径中有空格的os.system

时间:2019-06-17 04:39:15

标签: python system

我正在尝试使用os.system来调用C:/Program Files中的程序。

该目录名称中的空格使每次尝试都变得混乱。这是我的代码:

cmd = 'C:Program Files\OpenSCAD\openscad.exe -o block0.stl block0.scad'
print cmd
os.system(cmd)

太空毁了一切。我已经尝试了此处列出的五个版本的标点符号(包括其他文章中推荐的一些版本)以及源标点符号,Python看到的结果字符串以及os.system的结果。

您如何标点正确呢?

cmd = 'C:Program Files\OpenSCAD\openscad.exe -o block0.stl block0.scad'

C:Program Files\OpenSCAD\openscad.exe -o block0.stl block0.scad
'C:Program' is not recognized as an internal or external command,
operable program or batch file.

cmd = 'C:"Program Files"\OpenSCAD\openscad.exe -o block0.stl block0.scad'

C:"Program Files"\OpenSCAD\openscad.exe -o block0.stl block0.scad
The system cannot find the path specified.

cmd = 'C:"Program Files\OpenSCAD\openscad.exe" -o block0.stl block0.scad'

C:"Program Files\OpenSCAD\openscad.exe" -o block0.stl block0.scad
The system cannot find the path specified.

cmd = 'C:\"Program Files\OpenSCAD\openscad.exe\" -o block0.stl block0.scad'

同一件事


cmd = 'C:""Program Files\OpenSCAD\openscad.exe"" -o block0.stl block0.scad'

C:""Program Files\OpenSCAD\openscad.exe"" -o block0.stl block0.scad
'C:""Program' is not recognized as an internal or external command,
operable program or batch file.

cmd = r'C:Program Files\OpenSCAD\openscad.exe -o block0.stl block0.scad'

(推荐here

C:Program Files\OpenSCAD\openscad.exe -o block0.stl block0.scad
'C:Program' is not recognized as an internal or external command,
operable program or batch file.

1 个答案:

答案 0 :(得分:2)

您几乎经历了几次。问题是您需要放置两个反斜杠,因为反斜杠是Python字符串中的转义字符,或者您可以使用带有r前缀的原始字符串。但是,无论哪种情况,您都必须在C:之后加上反斜杠,并在名称中包含空格的部分加上引号。以下任何示例均应起作用:

cmd = 'C:\\"Program Files\\OpenSCAD\\openscad.exe" -o block0.stl block0.scad'
cmd = r'C:\"Program Files\OpenSCAD\openscad.exe" -o block0.stl block0.scad'
cmd = "\"C:\\Program Files\\OpenSCAD\\openscad.exe\" -o block0.stl block0.scad"
cmd = r'"C:\Program Files\OpenSCAD\openscad.exe" -o block0.stl block0.scad'

请注意,您将无法使用双引号和原始Python字符串,因为您将无法转义双引号和字符串中的路径。