passing Python assignment value to shell
Cameron Simpson
cs at zip.com.au
Thu May 29 01:10:24 EDT 2014
On 28May2014 21:48, Satish Muthali <satish.muthali at gmail.com> wrote:
>This is what I went about doing:
>
> reecalc = [s.split() for s in os.Popen("free -ht").read().splitlines()]
I think you dropped an "f" in your cut/paste. Try to be precise.
> freecalc_total = freecalc[4]
> freecalc_total = freecalc_total[3]
> freecalc_total = freecalc_total.translate(None, 'M )
This is syntacticly invalid. Did this really come from working code?
Also, .translate does not accept None as its first argument.
> tmp = "%s" % freecalc_total
If freecalc_total is a string (as it seems from the above) then this line does
nothing.
If freecalc_total were a number, it would probably be better to use "%d"
instead of "%s"; %d will emit an error if freecalc_total is not a number, a
useful sanity check.
> command = "stressapptest -M %s -s 20" % tmp
> p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=
>subprocess.PIPE).communicate()[0]
>
>Please let me know if this is the optimal method to achieve in order to pass
>the assignment value to shell. I am open to suggestions or a better way of
>implementation/logic.
It is better to avoid shell=True unless you really need to run a shell command
(shell syntax or control structures, etc). This is because by plonking "%s" in
the middle of your shell string, you leave yourself open to "injection"
accidents (or attacks, of you can be tricked in the values you substitute).
Since you are running a command with known arguments and no shell syntax, you
do not need the shell. So just construct the arguments directly:
[ "stressapptest", "-M", str(freecalc_total), "-s", "20" ]
and set shell=False.
Cheers,
Cameron Simpson <cs at zip.com.au>
More information about the Python-list
mailing list