SymPy中如何美化输出到文件?及宽度限制问题解决
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
widthparameter directly topprintwith your desired column count:sp.pprint(a, width=150) # Use any width that fits your window - Set global width for all prints: Use
init_printingat 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

