import subprocess # Run the "ls" command to list the files in the current directory result = subprocess.run(["ls"]) # Print the command's return code print(f'Return code: {result.returncode}')
To execute a program or call a system command in Python, you can use the subprocess module. This module provides functions for running external commands, redirecting their input and output, and obtaining their return codes.
In the example above, the subprocess.run() method is used to run the ls command, which lists the files in the current directory. The result variable contains information about the command's return code, which indicates whether the command was successful or not. In this case, the result.returncode attribute is printed to the screen. The subprocess module provides a number of other functions for running commands and working with their output. For example, you can use the subprocess.check_output() function to capture the output of a command and return it as a string:
import subprocess # Run the "ls" command and capture its output output = subprocess.check_output(["ls"]) # Print the output as a string print(output.decode())
In this example, the ls command is run and its output is captured by the check_output() function. The output variable contains the command's output as a bytes object, which is decoded into a string and printed to the screen.
Overall, the subprocess module provides a powerful and flexible way to run external commands and work with their output in Python. It can be used to automate a wide variety of tasks and integrate Python with other tools and programs.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.