Skip to content Skip to sidebar Skip to footer

Assign Output Of Print To A Variable In Python

i want to know how to assign the output of print to a variable. so if mystring = 'a=\'12\'' then print mystring a=12 and i want to pass this like **kwargs, test(mystring)

Solution 1:

Redirect stdout and capture its output in an object?

import sys

# a simple class with a write method
class WritableObject:
    def __init__(self):
        self.content = []
    def write(self, string):
        self.content.append(string)

# example with redirection of sys.stdout
foo = WritableObject()                   # a writable object
sys.stdout = foo                         # redirection

print "one, two, three, four"            # some writing

And then just take the "output" from foo.content and do what you want with it.

Please disregard if I have misunderstood your requirement.


Solution 2:

You can call __str__ and __repr__ on python objects to get their string representations (there's a tiny difference between them, so consult the docs). That's actually done by print internally.


Solution 3:

I wouldn't do it that way, personally. A far less hackish solution is to build a dictionary from your data first, and then pass it whole to a function as **kwargs. For example (this isn't the most elegant way to do it, but it is illustrative):

import re

remove_non_digits = re.compile(r'[^\d.]+')

inputList = ["a='0.015in' lPrime='0.292' offX='45um' offY='75um' sPrime='0.393' twistLength='0'",
 "a='0.015in' lPrime='0.292' offX='60um' offY='75um' sPrime='0.393' twistLength='0'",
 "a='0.015in' lPrime='0.292' offX='75um' offY='75um' sPrime='0.393' twistLength='0'", '']

#remove empty strings
flag = True
while flag:
    try:
        inputList.remove('')
    except ValueError:
        flag=False

outputList = []

for varString in inputList:
    varStringList = varString.split()
    varDict = {}
    for aVar in varStringList:
        varList = aVar.split('=')
        varDict[varList[0]] = varList[1]
    outputList.append(varDict)

for aDict in outputList:
    for aKey in aDict:
        aDict[aKey] = float(remove_non_digits.sub('', aDict[aKey]))

print outputList

This prints:

[{'a': 0.014999999999999999, 'offY': 75.0, 'offX': 45.0, 'twistLength': 0.0, 'lPrime': 0.29199999999999998, 'sPrime': 0.39300000000000002}, {'a': 0.014999999999999999, 'offY': 75.0, 'offX': 60.0, 'twistLength': 0.0, 'lPrime': 0.29199999999999998, 'sPrime': 0.39300000000000002}, {'a': 0.014999999999999999, 'offY': 75.0, 'offX': 75.0, 'twistLength': 0.0, 'lPrime': 0.29199999999999998, 'sPrime': 0.39300000000000002}]

Which appears to be exactly what you want.


Solution 4:

for more of an explanation: i have a list of strings i got from a a comment line of a data file. it looks like this:

"a='0.015in' lPrime='0.292' offX='45um' offY='75um' sPrime='0.393' twistLength='0'",
 "a='0.015in' lPrime='0.292' offX='60um' offY='75um' sPrime='0.393' twistLength='0'",
 "a='0.015in' lPrime='0.292' offX='75um' offY='75um' sPrime='0.393' twistLength='0'",
 '']

i want to put the values into some structure so i can plot the various things versus any variabls so the list is a legend basically, and i want to plot functions of the traces versus variables given in teh legend.

so if for each entry i have a trace, then i may want to plot max(trace) vs offX for a series of a values.


Solution 5:

I believe one of these two things will accomplish what you're looking for:

The Python exec statement: http://docs.python.org/reference/simple_stmts.html#exec or the Python eval function: http://docs.python.org/library/functions.html#eval

Both of them let you dynamically evaluate strings as Python code.

UPDATE:

What about:

def calltest(keywordstr):
    return eval("test(" + keywordstr + ")")

I think that will do what you're looking for.


Post a Comment for "Assign Output Of Print To A Variable In Python"