[Tutor] System output into variable?

Walter Prins wprins at gmail.com
Thu Apr 3 19:14:09 CEST 2014


Hi Leam,


On 3 April 2014 15:24, leam hall <leamhall at gmail.com> 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"
>
> So far the best I've seen is:
>
> line = os.popen('ls -l my_file', stdout=subprocess.PIPE, shell=True)
> (out, err) = line.communicate()
>
> With no way to make 'my_file' a variable.


If you use IPython, this can be as simple as the following (this is on
windows, so 'ls -l' has been replaced by 'dir'):

Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.

IPython 1.0.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: my_file='virtualenv.exe'

In [2]: my_var=!dir {my_file}

In [3]: print my_var
[' Volume in drive C has no label.', ' Volume Serial Number is
E8D7-900D', '', ' Directory of C:\\Python27\\Scripts', '', '2011/06/24
 11:12             7\xff168 virtualenv.exe', '               1 File(s)
      7\xff168 bytes', '               0 Dir(s)
47\xff655\xff469\xff056 bytes free']

In [4]:


Walter


More information about the Tutor mailing list