Python running exe file
Running an EXE File with Python
In Python, we often encounter situations where we need to run EXE files, such as calling other programming languages or running standalone executable programs. This article will detail how to run EXE files using Python, including using the os module, the subprocess module, and EXE files packaged with PyInstaller.
Running an EXE File with the os Module
The os module is part of Python’s standard library and provides functions for interacting with the operating system. Using the os module, we can use the os.system()
function to run EXE files.
The following is a simple example code that demonstrates how to use the os module to run an EXE file:
import os
exe_path = "C:/Program Files/Notepad++/notepad++.exe"
os.system(exe_path)
In the above code, we specify the path to the EXE file and use the os.system()
function to run it. When you run this code, the system automatically opens the EXE file at the specified path.
Using the subprocess module to run an EXE file
The subprocess module is a high-level API provided by Python for creating and interacting with subprocesses. Compared to the os module, the subprocess module provides richer functionality and more flexible usage.
The following is an example code using the subprocess module to run an EXE file:
import subprocess
exe_path = "C:/Program Files/Notepad++/notepad++.exe"
subprocess.call([exe_path])
In the above code, we use the subprocess.call()
function to run the EXE file, passing the EXE file path as a parameter. Unlike the os module, the subprocess module provides more control over the subprocess’s input, output, and errors.
Exe File Packaged Using PyInstaller
Sometimes, we need to package a Python script into a standalone executable program so that it can run in an environment without a Python interpreter installed. PyInstaller is a commonly used Python packaging tool that can package Python scripts into EXE files.
First, you need to install pyinstaller:
pip install pyinstaller
Then, run pyinstaller with the following command to package the Python script:
pyinstaller your_script.py
After packaging, an .exe file will be generated in the dist directory. You can double-click it to run it.
Summary
This article introduced how to run .exe files using Python. The os and subprocess modules allow us to conveniently execute external programs. Using .exe files packaged with pyinstaller allows us to run Python programs even in environments where the Python interpreter is not installed.