[Tutor] System output into variable?

Alan Gauld alan.gauld at btinternet.com
Thu Apr 3 19:42:19 CEST 2014

On 03/04/14 14:24, leam hall wrote:
> I've been trying to so a simple "run a command and put the output into a
> variable". Using Python 2.4 and 2.6 with no option to move. The go is to
> do something like this:
> my_var = "ls -l my_file"

I'm not sure what you mean here?
What should my_var contain? The command string or the result of the 
command? In this case that would be a long file listing including all 
the access, size info etc?

> So far the best I've seen is:
> line = os.popen('ls -l my_file', stdout=subprocess.PIPE, shell=True)
> (out, err) = line.communicate()

Don't use os.popen(), it should be viewed as legacy code.
Use subprocess instead. There are several options including the call()
function, or the full blown Popen class.

> With no way to make 'my_file' a variable.

In your original version you could use string formatting to insert the 
file name but using subprocess the issue goes away because you build the 
command as a list of substrings, one of which is the file(in your case) 
and it can be a variable or literal as you require.

> I've got to be missing something, but I'm not sure what. Python has
> always impressed me a a language without a lot of hoops to go through.

subprocess can be a tad daunting but it is very powerful and once you 
get the hang of it quite straightforward.

Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list