subprocess cp目标文件为空

时间:2014-12-17 17:05:53

标签: python subprocess

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

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或自行创建临时文件并清理

1 个答案:

答案 0 :(得分:0)

解决了这个问题。调用tempfile时,cp仍然可以写入,并且在尝试复制时写入没有刷新到磁盘。

相关问题