开发者

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 outpu开发者_开发技巧t.

e.g.,

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

will output taken to the shell.


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


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!


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.


try subprocess.check_output.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜