mDya5
mDya5

Reputation: 31

Getting shell output with Python?

I have a shell script that gets whois info for domains, and outputs taken or available to the shell depending on the domain.

I'd like to execute the script, and be able to read this value inside my Python script.

I've been playing around with subprocess.call but can't figure out how to get the output.

e.g.,

subprocess.call('myscript www.google.com', shell=True)

will output taken to the shell.

Upvotes: 3

Views: 6742

Answers (4)

Adin Scannell
Adin Scannell

Reputation: 149

Manually using stdin and stdout with Popen was such a common pattern that it has been abstracted into a very useful method in the subprocess module: communicate

Example:

p = subprocess.Popen(['myscript', 'www.google.com'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
(stdoutdata, stderrdata) = p.communicate(input="myinputstring")
# all done!

Upvotes: 6

Michael Lorton
Michael Lorton

Reputation: 44386

try subprocess.check_output.

Upvotes: 1

sarnold
sarnold

Reputation: 104050

subprocess.call() does not give you the output, only the return code. For the output you should use subprocess.check_output() instead. These are friendly wrappers around the popen family of functions, which you could also use directly.

For more details, see: http://docs.python.org/library/subprocess.html

Upvotes: 8

richo
richo

Reputation: 8989

import subprocess as sp
p = sp.Popen(["/usr/bin/svn", "update"], stdin=sp.PIPE, stdout=sp.PIPE, close_fds=True)
(stdout, stdin) = (p.stdout, p.stdin)
data = stdout.readline()
while data:
    # Do stuff with data, linewise.

    data = stdout.readline()
stdout.close()
stdin.close()

Is the idiom I use, obviously in this case I was updating an svn repository.

Upvotes: 5

Related Questions