Ask Your Question
0

access to printed output

asked 2013-11-29 04:05:06 -0600

anonymous user

Anonymous

Maybe relating to this question: Access output from previous cells

Assume I defined a function that takes a string and prints it:

def f(s):
    print s
    return

Now the output of the cell

f('hello')

is just the word 'hello'.

Is there any way to access this output, for example read it as a variable?

The problem occurs when I have a MixedIntegerLinearProgram p and access it with p.show(). I then want to do something with the printed output of this command, e.g. write it to a file.

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
2

answered 2013-11-30 04:28:34 -0600

tmonteil gravatar image

updated 2013-11-30 04:33:55 -0600

When the .show() method of a MixedIntegerLinearProgram prints something, it is usually sent in the standard output of the shell that called your script. So, if the method was called from a script in a terminal, cou can catch it as usually (e.g. with pipelines | or >).

If the command is launched from a ipython shell, it is catched by ipython and printed in the ipython shell. You can access to it as follows:

sage: p = MixedIntegerLinearProgram()
sage: from IPython.utils import io
sage: with io.capture_output() as captured:
....:     p.show()

Then you got the result in the captured object:

sage: captured
<IPython.utils.io.CapturedIO at 0xbf0916c>
sage: print captured
Maximization:

Constraints:
Variables:
sage: str(captured)
'Maximization:\n \nConstraints:\nVariables:\n'

It both works on the sage command line and in the notebook.

edit flag offensive delete link more
0

answered 2013-11-30 02:57:08 -0600

Luca gravatar image

In python, there is no easy way to catch the printed output of a function. I don't know if there is a hard way to do it in the notebook :)

In your case, you can't easily intercept the output of MixedIntegerLinearProgram.show(). str(p) will return a string representation (rather than printing it) of your MIP, which you can write to a file.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-11-29 04:05:06 -0600

Seen: 245 times

Last updated: Nov 30 '13