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'
In Python 3.5:
I had the same problem But figured out a very simple way of doing this follow this
Hope it helps out
Note: This solution is python3 specific as
subprocess.getoutput()
don't work in python2Modern Python solution (>= 3.1):
Splitting the initial command for the
subprocess
might be tricky and cumbersome.Use
shlex.split
to help yourself out.Sample command
git log -n 5 --since "5 years ago" --until "2 year ago"
The code
You can use following commands to run any shell command. I have used them on ubuntu.
This is way easier, but only works on Unix (including Cygwin).
it returns a tuple with the (return_value, output)
This only works in
python2.7
: it is not available onpython3
. For a solution that works in both, use thesubprocess
module instead: