2012-04-11 36 views
5

我已经成功地找到代码生成一个vim编辑和创建从python脚本一个临时文件。该代码是在这里,我在这里找到:call up an EDITOR (vim) from a python scriptvim编辑器在Python脚本临时文件

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脚本一旦被编辑与编辑器?

谢谢

回答

5

里面的东西一个with块的作用范围。如果您创建具有with声明的临时文件,块结束后,将不可用。

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

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

如果你想自动关闭该文件的块之后,但仍能够重新打开它,通过delete=FalseNamedTemporaryFile构造函数(否则它会闭幕后删除):

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

顺便说一句,你可能需要使用envoy运行子进程,正冰库:)

+0

非常感谢您 – Neeran 2012-04-11 10:45:12

2

NamedTemporaryFile创建一个关闭后删除的文件(docs)。因此,它不适合当你需要写的东西到一个临时文件和文件被关闭后,读取其中的内容。

使用mkstemp代替(docs):

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

我没不知道“delete = False”(请参阅​​接受的答案)。无论如何,我会留下我的答案,因为它显示了解决问题的另一种有效方法。 – codeape 2012-04-11 11:36:55

3

我也陷入了同样的问题,并有同样的问题。

它只是不觉得自己是一个最好的做法不删除临时文件只是这样,它可以被读出。我发现下面的方式来阅读什么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() 

这是我在脚本中使用的实际代码: 进口临时文件 进口OS 从子导入调用

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()