Search code examples
pythonfile-iosympypprint

How to pretty print to a file in sympy?


Suppose I have the following code:

import sympy as sp
from sympy.physics.quantum import TensorProduct

s=sp.eye(2)
a=TensorProduct(s*x,TensorProduct(s,s)).subs(x,x**2+2*x+1)
sp.pprint(a)

The code will generate an output with a limited widths (which I hate):

enter image description here

My questions are:

  1. Why there is a width limit while my window has enough space and how to change it?
  2. How to print such an output to a file?

Solution

  • For python>=3.4,

    from contextlib import redirect_stdout
    import sympy as sp
    from sympy.physics.quantum import TensorProduct
    
    s = sp.eye(2)
    x = sp.symbols('x')
    a = TensorProduct(s*x, TensorProduct(s, s)).subs(x, x**2+2*x+1)
    
    with open('data.txt', 'w') as f:
        with redirect_stdout(f):
            sp.pprint(a, wrap_line=False)
    

    .