[Python] Running shell command and capturing the output

Discussão em 'Python' iniciado por Stack, Maio 30, 2025.

  1. Stack

    Stack Membro Participativo

    I want to write a function that will execute a shell command and return its output as a string, no matter, is it an error or success message. I just want to get the same result that I would have gotten with the command line.

    What would be a code example that would do such a thing?

    For example:

    def run_command(cmd):
    # ??????

    print run_command('mysqladmin create test -uroot -pmysqladmin12')
    # Should output something like:
    # mysqladmin: CREATE DATABASE failed; error: 'Can't create database 'test'; database exists'

    Continue reading...

Compartilhe esta Página