Home >Backend Development >Python Tutorial >How to Execute a Program with Spaces in the Path from Python?

How to Execute a Program with Spaces in the Path from Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 15:08:03475browse

How to Execute a Program with Spaces in the Path from Python?

How to Execute a Program from Python

Python provides a convenient way to execute external programs using the os.system() function. However, this function can fail when the path to the program contains spaces.

Solution: Using subprocess.call()

The subprocess.call() function is an alternative to os.system() that avoids quoting issues caused by spaces in the path. It takes a list of arguments instead of a single string, simplifying argument delimitation.

<code class="python">import subprocess

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

In this example, Notepad.exe will be executed with the parameter C:\test.txt. The subprocess.call() function will wait until the program completes.

Other Options

1. Escaping Spaces

Enclosing the path in double quotes can escape spaces. However, this method can become cumbersome when adding multiple parameters.

<code class="python">os.system('"C:\Temp\a b c\Notepad.exe" "C:\test.txt"')</code>

2. Using Shell=True with os.system()

Setting shell=True allows the operating system's command interpreter to handle quoting conventions. However, this method comes with security risks.

<code class="python">os.system("C:\Temp\a b c\Notepad.exe C:\test.txt", shell=True)</code>

Conclusion

subprocess.call() is the preferred method for executing a program from Python when the path contains spaces. It provides a straightforward and secure solution.

The above is the detailed content of How to Execute a Program with Spaces in the Path from Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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