我已经成功地找到了生成 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/