摘要:一个只有 5 行的 Python 脚本,用
sudo -u pytest nohup python test.py &起了七八次都起不来,报错还从Errno 13变成Errno 2再变成"日志一片空白"。本文复盘这三个独立叠加的坑 —— 它们分别对应 Linux 里三个高频误区:目录的 x 权限、相对路径、Python 缓冲。适合人群:Linux 初学者 / 运维 / 用 nohup 或 systemd 跑脚本的同学 关键词:nohup、Errno 13、Errno 2、权限、相对路径、Python 缓冲、排错
一、坑 1:Errno 13 Permission denied —— 目录缺 x 权限
python: can't open file '/home/admin/test.py': [Errno 13] Permission denied
很多人第一反应是"文件权限不对"。但看一眼文件其实是好的:
$ ls -l /home/admin/test.py
-rwxr--r-- 1 pytest pytest 91 ... test.py # 属主 pytest,可读,没问题
$ ls -ld /home/admin
drwx------ 11 admin admin 4096 ... /home/admin # <- 问题在这里(700)
Linux 访问一个文件,要求路径上每一级目录都有 x(执行/穿越)权限。
/home/admin 是 700,pytest 用户连"进这个目录"都不行,文件权限再宽也没用。
定位命令:
$ namei -l /home/admin/test.py
drwxr-xr-x root root /
drwxr-xr-x root root home
drwx------ admin admin admin <- 断在这里
-rwxr--r-- pytest pytest test.py <- 文件本身没问题
旁证:nohup 提示写到了 /home/pytest/nohup.out 而不是 ./nohup.out —— 说明 pytest 连当前目录的写权限都没有,被迫回退到家目录。这一行其实早就把问题告诉你了。
修法:
# 方案一(推荐):把脚本放到目标用户能访问的目录
cp /home/admin/test.py /home/pytest/
chown pytest:pytest /home/pytest/test.py
# 方案二:只给该用户目录穿越权(不影响其他人)
setfacl -m u:pytest:x /home/admin
二、坑 2:Errno 2 No such file —— 相对路径 + 文件没搬
解决了权限,第二次又报:
python: can't open file '/home/pytest/test.py': [Errno 2] No such file or directory
因为 python test.py 是相对路径,以"当前工作目录"为基准。
你 cd /home/pytest 之后,python 只认 /home/pytest/test.py —— 可文件根本没复制过去。
$ ls -la /home/pytest/
-rw-r--r-- .bashrc
-rw-r--r-- .bash_profile
-rw------- nohup.out <- 连 test.py 的影子都没有
两个错误含义完全不同,别混为一谈:
| 报错 | 含义 | 排查方向 |
|---|---|---|
Errno 13 Permission denied | 文件在,但路径上某级目录没有 x 权限 | namei -l |
Errno 2 No such file | 文件根本不在那个路径 | 先 pwd + ls 确认 |
三、坑 3:日志一片空白 —— Python 输出缓冲
sudo -u pytest nohup python test.py &
ps -ef | grep test.py # 进程在跑
ls -l nohup.out # 0 字节
tail -f nohup.out # 什么都没有
不是没输出,是 Python 把输出攒在缓冲区里了。
输出到终端是行缓冲(每行立刻可见);输出到文件是块缓冲(攒满 4~8KB 才写)。脚本每秒只写 14 字节,攒满 4096 字节要 292 秒。
修法:
python -u test.py # (1) 运行时无缓冲
print("...", flush=True) # (2) 脚本内主动冲刷
env PYTHONUNBUFFERED=1 python test.py # (3) 环境变量
实测:不加
-u跑 3 秒,日志 0 行;加了之后 3 行。
四、最终可用的命令
cd /home/pytest
sudo -u pytest nohup python -u test.py > /home/pytest/run.log 2>&1 &
tail -f /home/pytest/run.log
三条硬性要求:
- 脚本在该用户能读到的路径
- 用
-u或flush=True解决缓冲 >后面的文件 和tail后面的文件必须是同一个
五、排查清单
namei -l <脚本路径> # 路径权限逐级看
ls -l <脚本路径> # 文件存在吗、权限对吗
ps -C python -o pid,user,etime,cmd # 进程在跑吗、命令行长什么样
ls -l <日志文件> # 日志在涨吗(不涨 = 缓冲)
readlink /proc/<PID>/fd/1 # 进程的 stdout 到底指向哪
六、结论
Errno 13查目录 x 权限,Errno 2查文件是否存在 —— 两个错含义完全不同。 日志空白先怀疑缓冲,-u或flush=True解决。 后台任务的输出目标由启动命令决定,> file就该和tail file对上。
评论
留言
无需注册,留个名字即可。理性发言,彼此尊重。
正在载入留言…