Hi Everyone :-)
I'm writing a small Python script that invokes the Linux shell and runs some BASH commands in it.
My problem is, I can't seem to use the output and store it in a Python variable.

Here's what i'm trying:

import subprocess

value = subprocess.call("ls -la", shell=True)
print(variable)

What happens is that the "ls -la" command is executed just fine in the shell window, but the variable "value" is empty.
what am i missing here?

Thanks for the help :-)

Probably, you want to print(value) instead.

PS: note that subprocess.call returns the exit status, not the output. You may want to redirect stdout.

Edited 6 Years Ago by nezachem: n/a

Yes, sorry (thanks for the correction) - the last statement should be:

...
print(value)

How do I redirect stdout? how do i store it into a Python variable?

Many thanks for your help :-)

This code was part of one post earlier in DaniWeb, I did not have energy now to pin point the post so I include it here (it was about polish characters I think)

This code seems to have difficulty in doing ls or (dir) in root directory in WindowsXP at least.

# from one discussion thread in Daniweb
import os

class Command(object):
    """Run a command and capture it's output string, error string and exit status"""

    def __init__(self, command):
        self.command = command 

    def run(self, shell=True):
        import subprocess as sp
        process = sp.Popen(self.command, shell = shell, stdout = sp.PIPE, stderr = sp.PIPE)
        self.pid = process.pid
        self.output, self.error = process.communicate()
        self.failed = process.returncode
        return self

    @property
    def returncode(self):
        return self.failed

com = Command("ls -la").run()
print com.output
print com.error

Edited 6 Years Ago by pyTony: n/a

os.popen returns an object that you can assign to a variable and iterate through. I read about it at http://linux.byexamples.com/archives/366/python-how-to-run-a-command-line-within-python/

>>> import os
>>> f=os.popen("ls -la")
>>> for i in f.readlines():
	print "myresult:", i,

	
myresult: total 9804
myresult: drwxr-xr-x 55 david david    4096 2010-05-04 16:28 .
myresult: drwxr-xr-x  3 root  root     4096 2010-02-25 16:05 ..
myresult: drwx------  3 david david    4096 2010-02-26 14:37 .adobe
myresult: -rw-------  1 david david    9596 2010-05-03 11:38 .bash_history
etc......................
This question has already been answered. Start a new discussion instead.