Nee*_*ran 5 python vim file temporary-files
我成功地找到了生成vim编辑器和从python脚本创建tempfile的代码.代码在这里,我在这里找到它:从python脚本调用EDITOR(vim)
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])
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是我退出编辑器后无法访问临时文件的内容.
tempfile
<closed file '<fdopen>', mode 'w+b' at 0x87c47b0>
tempfile.readline()
Run Code Online (Sandbox Code Playgroud)
我明白了
ValueError: I/O operation on closed file
Run Code Online (Sandbox Code Playgroud)
我做了:
myfile = open(tempfile.name)
IOError: [Errno 2] No such file or directory: '/tmp/tmp7VKzfl.tmp'
Run Code Online (Sandbox Code Playgroud)
使用编辑器编辑后,如何在python脚本中访问该文件?
谢谢
with块内的所有内容都是作用域.如果使用该with语句创建临时文件,则在块结束后将无法使用该文件.
您需要读取with块内的tempfile内容,或使用其他语法来创建临时文件,例如:
tempfile = NamedTemporaryFile(suffix=".tmp")
# do stuff
tempfile.close()
Run Code Online (Sandbox Code Playgroud)
如果你想在阻止后自动关闭文件,但仍然可以重新打开它,则传递delete=False给NamedTemporaryFile构造函数(否则它将在关闭后删除):
with tempfile.NamedTemporaryFile(suffix=".tmp", delete=False) as tempfile:
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你可能想使用envoy来运行子进程,漂亮的库:)