How to Execute Programs with Spaces in Their Paths Using Python?

Linda Hamilton
Release: 2024-11-03 12:12:29
Original
842 people have browsed it

How to Execute Programs with Spaces in Their Paths Using Python?

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>
Copy after login

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.
Copy after login

To resolve this issue, escape the program with quotes:

<code class="python">os.system('"C:\Temp\a b c\Notepad.exe"');</code>
Copy after login

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>
Copy after login

To address this, utilize subprocess.call:

<code class="python">import subprocess

subprocess.call(['C:\Temp\a b c\Notepad.exe', 'C:\test.txt'])</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template