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'
Your Mileage May Vary, I attempted @senderle's spin on Vartec's solution in Windows on Python 2.6.5, but I was getting errors, and no other solutions worked. My error was:
WindowsError: [Error 6] The handle is invalid
.I found that I had to assign PIPE to every handle to get it to return the output I expected - the following worked for me.
and call like this, (
[0]
gets the first element of the tuple,stdout
):After learning more, I believe I need these pipe arguments because I'm working on a custom system that uses different handles, so I had to directly control all the std's.
To stop console popups (with Windows), do this:
I had a slightly different flavor of the same problem with the following requirements:
keyword above
I've combined and tweaked previous answers to come up with the following:
This code would be executed the same as previous answers:
This is a tricky but super simple solution which works in many situations:
A temporary file(here is tmp) is created with the output of the command and you can read from it your desired output.
Extra note from the comments: You can remove the tmp file in the case of one-time job. If you need to do this several times, there is no need to delete the tmp.
If you need to run a shell command on multiple files, this did the trick for me.
Edit: Just saw Max Persson's solution with J.F. Sebastian's suggestion. Went ahead and incorporated that.
eg, execute('ls -ahl') differentiated three/four possible returns and OS platforms:
function below
Vartec's answer doesn't read all lines, so I made a version that did:
Usage is the same as the accepted answer: