【问题标题】:python file is incomplete, how to wait till it is complete before handling back to parent processpython文件不完整,如何等到它完成后再处理回父进程
【发布时间】:2015-12-03 17:33:02
【问题描述】:

我希望能够启动一个将文件写入服务器的子进程,然后等到它完全完成后再处理回父进程。 我从发布请求中收到一个图像文件。我解析它并使用以下代码将其写入服务器......这很好。

path="/var/bla/bla/bla/"
original_fname = file1['filename']
output_file = open(os.path.join(path,original_fname), 'w')
output_file.write(file1['body'])

问题是我必须在创建后使用 imagemagick 命令行工具访问该文件以获取某些数据。但是使用上面的代码还为时过早,并且该过程还没有完成创建文件。 我想在上面的代码之后这样做......

subprocess.Popen(stdout=output_file)
Popen.communicate()

但出现以下错误....

'Popen' 对象没有属性 '_child_created'

我该如何解决这个问题?

【问题讨论】:

  • 您是否在完成写入后关闭文件?完成写入后尝试关闭文件。
  • 嗨,凯文,不。你会怎么做?
  • 在这种情况下,output_file.close().
  • 哈哈。是的。就是这样。把它放在答案中,。谢谢你。像往常一样,我试图使事情复杂化:)
  • 也应该是process = subprocess.Popen(stdout=outputfile)process.communicate()

标签: python subprocess popen


【解决方案1】:

您在写入文件后没有关闭它。你可以这样做:

output_file = open(os.path.join(path,original_fname), 'w')
output_file.write(file1['body'])
output_file.close()

但我建议使用with 关键字,即使块中发生错误,它也会关闭文件描述符:

with open(os.path.join(path,original_fname), 'w') as output_file:
    output_file.write(file1['body'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 2016-06-13
    • 2015-08-13
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多