2

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.

1
  • 3
    What are you trying to achieve? It's not clear what you are actually trying to do, but if it's some eval()-like functionality it probably isn't a good idea. Commented Feb 23, 2010 at 21:44

6 Answers 6

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+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: 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.
+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.
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.

Comments

0

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.

2 Comments

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
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.
0

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.

Comments

0

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.

2 Comments

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

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.

1 Comment

i tried this and got a syntax error, im also not sure of the theory behind it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.