To execute the provided shell commands using Python, we can use the subprocess module. This module allows us to run shell commands from within a Python script. Since the commands include export (which sets environment variables) and source (which loads a script into the current shell), we need to ensure they are executed in the same shell session. This can be achieved by passing all commands as a single string to subprocess.run() with shell=True.
I'll use /bin/bash as the shell executable to ensure compatibility with Bash-specific commands like source.
Here's the Python code:
import subprocess
def execute_shell_commands():
# Define the commands as a multi-line string
commands = """
export MACHINE=sa525m
export DISTRO=qti-distro-tele-debug
source poky/qti-conf/set_bb_env.sh
sed -i '/SSTATE_MIRRORS:append.*$/d' conf/auto.conf
sed -i '/SSTATE_MIRRORS_append.*$/d' conf/auto.conf
"""
try:
# Run the commands using subprocess
result = subprocess.run(commands, shell=True, executable='/bin/bash', check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
# If successful, print the output
print("Commands executed successfully:")
print(result.stdout)
if result.stderr:
print("Warnings or errors from stderr:")
print(result.stderr)
except subprocess.CalledProcessError as e:
# Handle errors if any command fails
print(f"Error executing commands: {e}")
print(f"Command output: {e.output}")
print(f"Error details: {e.stderr}")
if __name__ == "__main__":
execute_shell_commands()
Explanation:
- subprocess.run(): This function executes the shell commands. We pass the entire block of commands as a string.
shell=True: Runs the commands in a shell, allowing them to be executed sequentially in the same environment.
executable='/bin/bash': Specifies Bash as the shell to handle commands like source.
check=True: Raises a CalledProcessError if any command returns a non-zero exit code.
stdout=subprocess.PIPE and stderr=subprocess.PIPE: Captures the output and errors for display.
text=True: Ensures the output is returned as strings instead of bytes.
- Error Handling: The code catches
CalledProcessError to handle cases where commands fail (e.g., file not found or permission issues).
- : The script prints the stdout and stderr for visibility.