Ask Your Question

access to printed output

asked 2013-11-29 11:05:06 +0200

anonymous user


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

Now the output of the cell


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

answered 2013-11-30 11:28:34 +0200

tmonteil gravatar image

updated 2013-11-30 11:33:55 +0200

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:

Then you got the result in the captured object:

sage: captured
< at 0xbf0916c>
sage: print captured

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

answered 2013-11-30 09:57:08 +0200

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


Asked: 2013-11-29 11:05:06 +0200

Seen: 1,366 times

Last updated: Nov 30 '13