子进程cp目标文件为空

2024-04-25 20:19:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写一个脚本,把它的输出写到一个系统目录。我没有使用根权限运行整个脚本,而是将输出写入临时文件,并且仅在将临时文件复制到输出时使用提升的权限。在

print(tempfile.read())
return_code = suprocess.call(['/usr/bin/sudo', 'cp', tmpfile.name, outfile])
if return_code != 0:
    print('Copy failed')
    sys.exit(1)
return_code = subprocess.call(['/usr/bin/sudo', 'chmod', '664', outfile])
with open(outfile) as f2:
    print(f2.read())

第一个调试输出生成文件的预期内容,但第二个dprint为空。此外,检查文件系统中的文件会发现该文件的长度为0个字节,由root用户拥有。在

我尝试了以下方法,但似乎没有什么不同:

  • 使用shell=True
  • 使用tempfile.NamedTempfile或自己创建一个临时文件并进行清理

Tags: 文件脚本权限readreturnbinusrsudo