You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SymPy中如何美化输出到文件?及宽度限制问题解决

Answers to Your SymPy Output Questions

1. Why the Width Limit Exists & How to Fix It

SymPy’s pprint (pretty printer) uses a default column width (typically 79 characters) by design—this is a legacy setting to ensure output fits in standard terminal windows and maintains readability across different systems. It doesn’t automatically detect your terminal’s current width unless you explicitly configure it.

Fixes:

  • Adjust width per pprint call: Pass the width parameter directly to pprint with your desired column count:
    sp.pprint(a, width=150)  # Use any width that fits your window
    
  • Set global width for all prints: Use init_printing at the start of your script to configure the default width for all subsequent pretty prints:
    import sympy as sp
    from sympy.physics.quantum import TensorProduct
    
    sp.init_printing(width=150)  # Global width setting
    s = sp.eye(2)
    a = TensorProduct(s*x, TensorProduct(s,s)).subs(x, x**2+2*x+1)
    sp.pprint(a)
    
  • Modify the printer’s global default: If you need even more control, you can adjust the base Printer class’s width:
    sp.printing.printer.Printer().width = 150
    

2. Printing Output to a File

You have two straightforward ways to save the pretty-printed output to a file:

Method 1: Use the file parameter in pprint

Open a file in write mode and pass it to the file argument of pprint. This works just like printing to the console but directs output to your file:

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)

# Write to file with custom width
with open('sympy_output.txt', 'w') as output_file:
    sp.pprint(a, width=150, file=output_file)

Method 2: Generate a pretty string and write it manually

If you want to process the output string before saving, use sp.pretty() to get the formatted string, then write it to the file:

pretty_str = sp.pretty(a, width=150)
with open('sympy_output.txt', 'w') as output_file:
    output_file.write(pretty_str)

Both methods will save the properly formatted tensor product to your specified file with the width you set.

内容的提问来源于stack exchange,提问作者Xiaoyu Liu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:08:47