open没权限
1.open修改文件没权限
每次都写入新的内容
msg_info = "test msg info"
msg_file_path = "/dev/shm/notify.txt"
with open(msg_file_path, "w") as f:
f.write(msg_info)
PermissionError: [Errno 13] Permission denied: '/dev/shm/notify.txt'
2.解法方法
2.1使用tee命令
tee命令可以将输出重定向到文件,并且可以绕过shell的权限限制。
不加> /dev/null会把内容输出到终端
终端无内容
echo 'test msg info'| sudo tee /dev/shm/notify.txt > /dev/null
终端有内容
# 命令会将输入的内容写入指定的文件,并同时将内容输出到标准输出(即终端)。这就是为什么你会在终端中看到test msg info的原因
echo 'test msg info' | sudo tee /dev/shm/notify.txt
test msg info
2.2 使用sudo和bash -c
将整个命令放在
bash -c中执行,确保sudo的权限生效
sudo bash -c 'echo "test msg info" > /dev/shm/notify.txt'
3.案列
msg_info = "test msg info"
msg_file_path = "/dev/shm/notify.txt"
try:
with open(msg_file_path, "w") as f:
f.write(msg_info)
except PermissionError:
cmd = f"sudo bash -c \"echo '{msg_info}' > {msg_file_path}\""
# cmd = f"echo '{msg_info}'| sudo tee {msg_file_path} > /dev/null"
subprocess.run(cmd, shell=True)

浙公网安备 33010602011771号