passing Python assignment value to shell

Ben Finney ben at benfinney.id.au
Wed May 28 19:45:02 EDT 2014


Satish Muthali <satish.muthali at gmail.com> writes:

> so, this is what I have so far:

Thank you for presenting your code. Please ensure that you post in text
only, without transforming the characters from what you typed.

Something in your message composition process is currently converting
some ‘"’ (U+0022 QUOTATION MARK) characters into ‘“’ and ‘”’ (U+201C
LEFT DOUBLE QUOTATION MARK and U+201D RIGHT DOUBLE QUOTATION MARK)
characters, which changes the meaning of your code. Best to turn off all
such automated conversions when you compose a message.

> reecalc = [s.split() for s in os.Popen("free -ht").read().splitlines()]
> freecalc_total = freecalc[4]
> freecalc_total = freecalc_total[3]
> freecalc_total = freecalc_total.translate(None, 'M’)
>
> Now I want to feed the value for ‘freecalc_total’ as an argument to a
> command executed by the shell.

It will need to be a text string representation of that number, since
the command line will be a sequence of text string arguments.

To create a text string representation of an integer, use
‘str(freecalc_total)’. (In Python 2, use ‘unicode(freecalc_total)’.)

If the number is not an integer, you should format it explicitly with a
format string <URL:https://docs.python.org/3/library/functions.html#format>::

    >>> freecalc_total = 80752.16
    >>> freecalc_arg = format(freecalc_total, "14.3f")
    >>> freecalc_arg
    '     80752.160'

> For example:
>
> devnull = open(os.devnull, “w”)
> runCommand = subprocess.call([“stressapptest”, “<I want to pass the value of freecalc_total here>”, “20”],stdout=devnull,stderr=subprocess.STDOUT)
> devnull.close()

(You should follow PEP 8 for your Python code, which recommends against
camelCaseNames and recommends spaces after commas for readability.)

So I'd suggest::

    freecalc_total = your_computations_as_above()
    foo_arg = 20    # You don't tell us what this argument is, but it should have a name.
    command_args = [
            "stressapptest",
            str(freecalc_total), str(foo_arg)]
    process = subprocess.call(
            command_args, stdout=devnull, stderr=subprocess.STDOUT)

> Many thanks in advance

I hope that helps.

-- 
 \       “Homer, where are your clothes?” “Uh... dunno.” “You mean Mom |
  `\        dresses you every day?!” “I guess; or one of her friends.” |
_o__)                                    —Lisa & Homer, _The Simpsons_ |
Ben Finney




More information about the Python-list mailing list