tags:

views:

95

answers:

6

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)

how can i do this?

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.

and my first idea was to pass the strings as **kwargs to a function which would produce a matrix of corresponding data.

+2  A: 

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.

jldupont
+1 mostly agree...eventually might want to re-access original sys.stdout to actually print something. so do this `sys_stdout_save = sys.stdout` before re-assigning sys.stdout
AJ
@AJ: of course one would prefer to `rewire` stdout at an appropriate time. It isn't really clear what the poster wants to achieve anyways IMO.
jldupont
+1 regardless of OP's actual intent, it is useful to know how to "hi-jack" sys.stdout. And yeah, one may want to preserve it to re-instate regular output at a later time but that is trivial.
mjv
A: 

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.

Zachary Murray
this is close but i cant get it to work. i want to evaluate a string and pass it to a function like kwargs
alex
Could you not do something like `eval("test(" + mystring + ")")`?
Zachary Murray
+1  A: 

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.

Alexander Gessler
A: 

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.

alex
A: 

If you have a string 'my_string' like this:

a=123 b=456 c='hello'

Then you can pass it to a function 'my_fun' like this:

my_fun(**eval('{' + my_string.replace(' ', ',') + '}'))

Depending on the precise formatting of my_string, you may have to vary this a little, but this should get you 90% of the way there.

Paul Hankin
i tried this and got a syntax error, im also not sure of the theory behind it.
alex
A: 

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.

Chinmay Kanchi
this is very good. a bit involved, but i think the best solution. this is problem arose because the plaintext file i am looking at is really a series of traces for many design variations. i just need a way to consolidate the data and look at somthing understandable, like Max(trace) vs parameterX, and all the parameters are given in the first line as a comment, but the order of these correspond to the order of the columns given in teh data portion. i hope this is clear and not very rambling. anyway, thanks a lot. alex
alex
This can almost certainly be done far more elegantly and in fewer lines of code. Also, if you think it's the best answer, please accept it.
Chinmay Kanchi