Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python command execution output [duplicate]

Tags:

python

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 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?

like image 703
user846121 Avatar asked Dec 21 '25 23:12

user846121


2 Answers

import subprocess
command = raw_input("Enter command: ")
p = subprocess.Popen(command, stdout=subprocess.PIPE)
output, error = p.communicate()
like image 193
agf Avatar answered Dec 24 '25 13:12

agf


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.

like image 35
Sean Vieira Avatar answered Dec 24 '25 11:12

Sean Vieira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!