开发者

Python command execution output [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Running shell command from python and capturing the output

I want to capture the output of a command into a variable, so later that variable can be used again. I need to change this script so it does that:

#!/usr/bin/python
import os
command = raw_input("Enter command: ")
os.system(command)

If I enter "ls" when I run this script, I get this output:

Documents Downloads Music Pictures Public Templates 开发者_Go百科Videos

I want to capture that string (the output of the ls command) into a variable so I can use it again later. How do I do this?


import subprocess
command = raw_input("Enter command: ")
p = subprocess.Popen(command, stdout=subprocess.PIPE)
output, error = p.communicate()


The output of the command can be captured with the subprocess module, specifically, the check_output function..

output = subprocess.check_output("ls")

See also the documentation for subprocess.Popen for the argument list that check_output takes.


This is the way I've done it in the past.

>>> import popen2
__main__:1: DeprecationWarning: The popen2 module is deprecated.  Use the subprocess module.
>>> exec_cmd = popen2.popen4("echo shell test")
>>> output = exec_cmd[0].read()
>>> output
'shell test\n'
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜