import subprocess
# 构建并执行命令
command = "sudo -i -u postgres -- bash -c 'cat /path/to/your/file.txt'"
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# 获取命令输出
output, error = process.communicate()
# 使用输出结果,类似于 'with open() as f' 的 'f'
if process.returncode == 0:
# 命令执行成功,处理输出
file_content = output.decode()
# 现在可以像处理文件对象一样处理file_content
print(file_content)
else:
# 命令执行失败,处理错误
print("Error:", error.decode())
python处理有权限读文件
于 2024-04-17 16:42:20 首次发布