Handling Program Execution with Spaces in Path Using Python
In Python, os.system is commonly used to execute external programs. However, it can fail when spaces are present in the path to the program.
Consider the following code snippet:
<code class="python">import os os.system("C:\Temp\a b c\Notepad.exe");</code>
This code attempts to execute Notepad with a path containing spaces. However, it fails with the error:
'C:\Temp\a' is not recognized as an internal or external command, operable program or batch file.
To resolve this issue, escape the program with quotes:
<code class="python">os.system('"C:\Temp\a b c\Notepad.exe"');</code>
However, this approach fails when passing parameters to the program, as seen in the following example:
<code class="python">os.system('"C:\Temp\a b c\Notepad.exe" "C:\test.txt"');</code>
To address this, utilize subprocess.call:
<code class="python">import subprocess subprocess.call(['C:\Temp\a b c\Notepad.exe', 'C:\test.txt'])</code>
subprocess.call accepts a list of arguments, eliminating the need for complex quoting. This effectively resolves the issue of executing programs with spaces in their paths.
The above is the detailed content of How to Execute Programs with Spaces in Their Paths Using Python?. For more information, please follow other related articles on the PHP Chinese website!