Linux下Shell脚本输出重定向至文本文件问题求助
Hey there! I see you're a Linux newbie stuck with a redirect issue—let's fix this together.
What's causing the problem?
When you run your script directly in the terminal, Python uses line buffering for stdout (standard output) by default. That means every print() statement sends content to the terminal right away. But when you redirect output to a file (like sh th.sh > output.txt), Python switches to block buffering: it stores output in a buffer until it's full, or until the script finishes running. So you won't see any content in the file until either of those things happens, which makes it look like nothing's working.
3 Fixes to Try
1. Disable Python output buffering with -u
The easiest fix is to add the -u flag when calling Python. This forces stdout to be unbuffered, so every line gets written to the file immediately. Modify your script like this:
python -u << END import time,random a= open ('/home/ch/pshety/course/fielding_history.txt','r') flag =False for i in range(1000): b=a.readline() if i==402 or flag: print(a.readline()) flag=True time.sleep(2) END
2. Add flush=True to your print statements
If you don't want to change how you call Python, you can tell each print() to immediately flush the buffer:
print(a.readline(), flush=True)
This overrides the default buffering behavior for that specific print call.
3. Set line buffering for stdout in Python
Another option is to reconfigure stdout to use line buffering, just like it does in the terminal. Add these lines at the top of your Python code:
import sys sys.stdout = open(sys.stdout.fileno(), 'w', buffering=1)
This sets stdout to line-buffered mode, so each line is written as soon as it's printed.
Test it out
After applying any of these fixes, run your script with redirect again (e.g., sh th.sh > my_output.txt). You should see lines appearing in the file every 2 seconds, just like they did in the terminal!
内容的提问来源于stack exchange,提问作者vbmolec

