Ask Your Question
0

access to printed output

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

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 11:28:34 +0100

tmonteil gravatar image

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

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 09:57:08 +0100

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 11:05:06 +0100

Seen: 1,525 times

Last updated: Nov 30 '13