You can run a Linux command in Python and save the output as a Python variable using the subprocess module. Here’s how you can do it:
- Import the
subprocessmodule. - Use the
subprocess.run()function to execute the command. - Capture the output by setting the
stdoutparameter tosubprocess.PIPE. - Decode the output from bytes to a string if needed.
Here’s an example:
pythonimport subprocess
# Run the command and capture the output
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, text=True)
# Save the output as a Python variable
output = result.stdout
# Print the output
print(output)
In this example, the ls -l command is executed, and its output is captured and stored in the output variable. The text=True parameter is used to ensure that the output is returned as a string instead of bytes.
Detailed Explanation:
subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, text=True):- The command
ls -lis passed as a list of arguments. stdout=subprocess.PIPEcaptures the standard output of the command.text=Trueensures that the output is returned as a string.
- The command
result.stdoutcontains the output of the command.
Another Example:
Here’s another example where we run the uname -a command to get system information:
pythonimport subprocess
# Run the command and capture the output
result = subprocess.run(['uname', '-a'], stdout=subprocess.PIPE, text=True)
# Save the output as a Python variable
output = result.stdout
# Print the output
print(output)
In this example, the uname -a command is executed, and its output is stored in the output variable.
Error Handling:
You can also add error handling to capture any errors that might occur during the execution of the command:
pythonimport subprocess
try:
# Run the command and capture the output
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
# Save the output as a Python variable
output = result.stdout
# Print the output
print(output)
except subprocess.CalledProcessError as e:
print(f"Error: {e.stderr}")
In this example, any errors during the execution of the command will be caught, and the error message will be printed. The check=True parameter ensures that an exception is raised if the command exits with a non-zero status.
No hay comentarios:
Publicar un comentario