python - python 脚本临时文件中的 Vim 编辑器

标签 python file vim temporary-files

我已经成功地找到了生成 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 脚本中访问该文件?

谢谢

最佳答案

with block 中的所有内容都是有作用域的。如果您使用 with 语句创建临时文件,它将在该 block 结束后不可用。

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

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

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

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

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

关于python - python 脚本临时文件中的 Vim 编辑器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10103359/

相关文章:

python - 如何将泰米尔语unicode值数组转换为带有空格的python中的泰米尔语字符串?

python - 将 CSV 转换为 txt 并使用 Python 每 10 个值开始新行

Vim 背景颜色无法在 GNOME 终端中正确呈现

vim - 如何将列数据划分为多列

python - 获取值大于前一个元素的 numpy 1d 数组的索引

python - 在其他系列的两个索引之间创建一个新的 pandas 系列

python - 如何将值映射到python中的模糊项

c - 在C中获取文件扩展名

android - 如何获得字符串数组的大小?

vim - 如何从命令提示符启动 Gvim?