[Tutor] System output into variable?
dyoo at hashcollision.org
Thu Apr 3 19:28:07 CEST 2014
On Thu, Apr 3, 2014 at 10:14 AM, Walter Prins <wprins at gmail.com> wrote:
> 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()
If you can, use the subprocess module instead. Also, avoid passing a
single string representing the command list, but rather pass a list.
This will also give you an easier opportunity to pass in variable data
to the external call.
cmd = subprocess.check_output(['ls', '-l', 'my_file'])
where it should be easier to see that you can replace any of the
string literals there, like 'my_file', with any other expression that
evaluates to a string value.
Do NOT use shell=True unless you really know what you're doing: you
can open a potential security hole in your programs if you use that
See the subprocess documentation for a few examples.
By the way, if you are trying to get information about the file, don't
depend on an external system call here. Use the standard library's
file stat functions. You'll have an easier time at it. See:
for more details.
More information about the Tutor