开发者

assign output of print to a variable in python

开发者 https://www.devze.com 2022-12-20 21:21 出处:网络
i want to know how to assign the output of print to a variable. so if mystring = \"a=\\\'12\\\'\" then

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开发者_JS百科?

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.


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.


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.


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号