Run Terminal Command in Python

How can I run terminal command in Python?

I read somewhere that you can execute terminal commands within a Python script, but I can’t seem to find the information now. I want to execute a command like ls -l from a Python script and output the result, just like running it in the terminal.

For example, the script should execute:

command 'ls -l'

And output the result of running that command in the terminal.

Ah, this is a common task! A straightforward way to run terminal command python is by using the os module. It’s simple and works for basic cases:

import os  
os.system("ls -l")  

This will execute the command and print the output directly to the terminal, just like you’d expect. However, it’s more of a quick and easy approach and doesn’t give you much control over the output or error handling.

Good start! But if you’re looking for more flexibility and control while you run terminal command python, the subprocess module is a better choice. With it, you can capture and process the output in your script. Here’s an example:

import subprocess  

test = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)  
output, errors = test.communicate()  

if test.returncode == 0:  
    print("Command output:")  
    print(output.decode())  
else:  
    print("Error:", errors.decode())  

This approach lets you handle errors, capture output, and work with commands dynamically. Plus, you can run much more complex operations using this module.

That’s great advice! If you want something even cleaner and more modern to run terminal command python, subprocess.run is a newer and more streamlined method introduced in Python 3.5. Here’s how it works:

import subprocess  

result = subprocess.run(["ls", "-l"], capture_output=True, text=True)  
if result.returncode == 0:  
    print("Command output:")  
    print(result.stdout)  
else:  
    print("Error:", result.stderr)  

This method is easy to use and recommended for most use cases. It directly provides access to the standard output (stdout), error output (stderr), and the return code, all in one place. Perfect for modern Python scripting!