如何在同事中打印到文件?

时间:2018-05-30 08:03:45

标签: python file-io sympy pprint

假设我有以下代码:

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)

代码将生成宽度有限的输出(我讨厌):

enter image description here

我的问题是:

  1. 为什么在我的窗口有足够的空间以及如何更改空间时有宽度限制?
  2. 如何将此类输出打印到文件?

1 个答案:

答案 0 :(得分:1)

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)