Running shell command and capturing the output

2018-12-31 01:44发布

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'

14条回答
呛了眼睛熬了心
2楼-- · 2018-12-31 02:11

In Python 3.5:

import subprocess

output = subprocess.run("ls -l", shell=True, stdout=subprocess.PIPE, 
                        universal_newlines=True)
print(output.stdout)
查看更多
孤独寂梦人
3楼-- · 2018-12-31 02:13

I had the same problem But figured out a very simple way of doing this follow this

import subprocess
output = subprocess.getoutput("ls -l")
print(output)

Hope it helps out

Note: This solution is python3 specific as subprocess.getoutput() don't work in python2

查看更多
像晚风撩人
4楼-- · 2018-12-31 02:13

Modern Python solution (>= 3.1):

 res = subprocess.check_output(lcmd, stderr=subprocess.STDOUT)
查看更多
初与友歌
5楼-- · 2018-12-31 02:13

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

from subprocess import check_output
from shlex import split

res = check_output(split('git log -n 5 --since "5 years ago" --until "2 year ago"'))
print(res)
>>> b'commit 7696ab087a163e084d6870bb4e5e4d4198bdc61a\nAuthor: Artur Barseghyan...'
查看更多
路过你的时光
6楼-- · 2018-12-31 02:15

You can use following commands to run any shell command. I have used them on ubuntu.

import os
os.popen('your command here').read()
查看更多
宁负流年不负卿
7楼-- · 2018-12-31 02:21

This is way easier, but only works on Unix (including Cygwin).

import commands
print commands.getstatusoutput('wc -l file')

it returns a tuple with the (return_value, output)

This only works in python2.7: it is not available on python3. For a solution that works in both, use the subprocess module instead:

import subprocess
output=subprocess.Popen(["date"],stdout=PIPE)
response=output.communicate()
print response
查看更多
登录 后发表回答