views:

104

answers:

5

So lets say I have an incredibly nested iterable of lists/dictionaries. I would like to print them to a file as easily as possible. Why can't I just redirect print to a file?

val = print(arg) gets a SyntaxError.

Is there a way to access stdinput?

And why does print take forever with massive strings? Bad programming on my side for outputting massive strings, but quick debugging--and isn't that leveraging the strength of an interactive prompt?

There's probably also an easier way than my gripe. Has the hive-mind an answer?

+1  A: 

Seeing how you're using print as function, docs say that you can redirect to file like this:

print(arg, file=open('fname', 'w'))
SilentGhost
**Always** use a context manager for `open`.
Mike Graham
+2  A: 

You could look into the logging module of Python. Perhaps that's the perfect match in this case.

bebraw
+1  A: 

In Python 3.*, to redirect one print call to an open file object destination,

print(arg, file=destination)

In Python 2.*, where print is a statement, the syntax is

print>>destination, arg

I imagine you're using 2.* because in 3.* assigning print's result is not a syntax error (it's just useless, since that result is None, but allowed). In 2.* print is a statement, not a function, so the code snippet you give is indeed a syntax error.

I'm not sure what the assignment is supposed to mean. If you want to redirect one or more print statements (or calls) to get the formatted result as an in-memory string, you can set sys.stdout to a StringIO (or cStringIO) instance; but you specifically mention "to a file" so I'm really perplexed as to the intended meaning of that assignment. Clarify pls?

Alex Martelli
You're right, I'm using 2.x. The issue is I need to output the result of parsing xml into data structures that are necessarily nested lists/dicts. Writing them to files was difficult, but printing them worked. Obviously it'd be better to write a validator, but this is a one-off thing that's a side project. The answer was the repr() function, which gets the string representation and allows me to work with that.
emcee
+1  A: 

You don't typically use print for writing to a file (though you technically can). You would use a file object for this.

with open(filename, 'w') as f:
    f.write(repr(your_thingy))

If print is taking forever to display a massive string, it is likely that it's not exactly print's fault, but the result of having to display all that to screen.

Mike Graham
That's exactly what I was looking for.The problem I was having with my nested list/dict is I couldn't easily write it to a file, but could easily print it. This is the best of both worlds.
emcee