【问题标题】:Vim Editor in python script tempfilepython脚本临时文件中的Vim编辑器
【发布时间】:2012-04-11 09:34:46
【问题描述】:

我已经成功地找到了用于生成 vim 编辑器并从 python 脚本创建临时文件的代码。代码在这里,我在这里找到了:call up an EDITOR (vim) from a python script

import sys, tempfile, os
from subprocess import call

EDITOR = os.environ.get('EDITOR','vim') 

initial_message = "" 

with tempfile.NamedTemporaryFile(suffix=".tmp") as tempfile:
  tempfile.write(initial_message)
  tempfile.flush()
  call([EDITOR, tempfile.name])

我遇到的问题是退出编辑器后无法访问临时文件的内容。

tempfile
<closed file '<fdopen>', mode 'w+b' at 0x87c47b0>

tempfile.readline()

我明白了

ValueError: I/O operation on closed file

我做到了:

myfile = open(tempfile.name)
IOError: [Errno 2] No such file or directory: '/tmp/tmp7VKzfl.tmp'

使用编辑器编辑文件后,如何在 python 脚本中访问该文件?

谢谢

【问题讨论】:

    标签: python file vim temporary-files


    【解决方案1】:

    with 块内的所有内容都是作用域。如果使用with 语句创建临时文件,则块结束后将无法使用。

    您需要读取with块内的临时文件内容,或使用其他语法创建临时文件,例如:

    tempfile = NamedTemporaryFile(suffix=".tmp")
    # do stuff
    tempfile.close()
    

    如果您确实想在块后自动关闭文件,但仍然能够重新打开它,请将 delete=False 传递给 NamedTemporaryFile 构造函数(否则它将在关闭后被删除):

    with tempfile.NamedTemporaryFile(suffix=".tmp", delete=False) as tempfile:
    

    顺便说一句,您可能想使用envoy 来运行子进程,不错的库:)

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题并且有同样的问题。

      不删除临时文件只是为了读取它,这感觉不是最佳做法。我找到了以下方法来读取 vim 编辑后写入 NamedTempFile 实例的内容,读取它,并保留删除临时文件的优势。 (如果不是自己删掉就不是临时的吧?!)

      必须倒回临时文件然后读取它。 我找到了答案:http://pymotw.com/2/tempfile/

      import os
      import tempfile
      from subprocess import call
      
      temp = tempfile.TemporaryFile()
      try:
          temp.write('Some data')
          temp.seek(0)
      
          print temp.read()
      finally:
          temp.close()
      

      这是我在脚本中使用的实际代码: 导入临时文件 导入操作系统 从子流程导入调用

      EDITOR = os.environ.get('EDITOR', 'vim')
      initial_message = "Please edit the file:"
      
      with tempfile.NamedTemporaryFile(suffix=".tmp") as tmp:
          tmp.write(initial_message)
          tmp.flush()
          call([EDITOR, tmp.name])
          #file editing in vim happens here
          #file saved, vim closes
          #do the parsing with `tempfile` using regular File operations
          tmp.seek(0)
          print tmp.read()
      

      【讨论】:

        【解决方案3】:

        NamedTemporaryFile 创建一个在关闭后删除的文件 (docs)。因此,它不适合当您需要向临时文件写入内容并在文件关闭后读取内容时。

        改用mkstemp (docs):

        f, fname = mkstemp(suffix=".tmp")
        f.write("...")
        f.close()
        call([EDITOR, fname])
        

        【讨论】:

        • 我不知道delete=False(请参阅接受的答案)。无论如何我都会留下我的答案,因为它显示了解决问题的另一种有效方法。
        猜你喜欢
        • 2017-06-17
        • 1970-01-01
        • 2012-02-27
        • 2015-05-01
        • 2016-12-11
        • 1970-01-01
        • 1970-01-01
        • 2018-02-23
        • 2016-04-11
        相关资源
        最近更新 更多