Executing External Programs from Python
Problem:
Executing external programs using os.system fails when the program path contains spaces. Escaping the program path with double quotes allows execution, but adding a parameter causes the program execution to fail again.
Solution:
To avoid issues related to quoting conventions and spaces in program paths, it's recommended to use the subprocess module. In particular, the subprocess.call function can execute programs and wait for their completion. Here's how to use it:
<code class="python">import subprocess # Create a list of arguments, including the program path and any arguments. args = ['C:\Temp\a b c\Notepad.exe', 'C:\test.txt'] # Execute the program using subprocess.call. subprocess.call(args)</code>
Explanation:
subprocess.call takes a list of arguments, making it easier to handle spaces and special characters in program paths and arguments. It also simplifies error handling and avoids potential shell-related issues. By using subprocess.call, you can reliably execute external programs from your Python script, even when the program path contains spaces.
The above is the detailed content of How to Execute External Programs with Spaces in the Path from Python?. For more information, please follow other related articles on the PHP Chinese website!