在 Debian 上使用 nohup 时日志出现“乱码”,通常不是 nohup 本身的问题,而是编码不一致导致的。下面按常见原因逐一说明和解决。
nohup xxx > log 2>&1 & 后,日志中文乱码nohup 启动的程序继承的是当前 shell 的环境变量,如果:
C / POSIX)程序可能输出非 UTF-8 编码,或认为终端不支持 UTF-8。
locale
如果看到:
LANG=C
LC_ALL=
就有问题。
设置为 UTF-8(推荐):
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
或修改 /etc/default/locale(Debian):
LANG=en_US.UTF-8
LC_ALL=en_US.UTF-8
然后重新登录或 source。
Python3 在 non-TTY(如 nohup 重定向)时:
ASCII 而不是 UTF-8解决:
export PYTHONIOENCODING=utf-8
nohup python3 app.py > log 2>&1 &
或在代码里:
import sys
sys.stdout.reconfigure(encoding='utf-8')
file log
iconv 转换:iconv -f gbk -t utf-8 log > log.utf8
或统一程序输出 UTF-8。
很多人误以为 nohup.out 乱码是 nohup 造成的:
✅ nohup 只是重定向 stdout/stderr ❌ 它不改变编码
locale
echo $LANG
file nohup.out
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
export PYTHONIOENCODING=utf-8
nohup your_program > app.log 2>&1 &
如果你能贴出:
locale 输出我可以帮你精确定位。