2010-04-05 183 views
1

我需要一种方法从外部编辑器获取数据。从外部程序获取数据

def _get_content(): 
    from subprocess import call 
    file = open(file, "w").write(some_name) 
    call(editor + " " + file, shell=True) 
    file.close() 
    file = open(file) 
    x = file.readlines() 

    [snip] 

我个人认为应该有更优雅的方式。你看,我需要与外部编辑器交互并获取数据。

你知道更好的方法/有更好的想法吗?

编辑:

马塞洛给我带来了使用上的tempfile这样做的想法。

这里是我如何做到这一点:

def _tempfile_write(input): 
    from tempfile import NamedTemporaryFile 

    x = NamedTemporaryFile() 
    x.file.write(input) 
    x.close() 
    y = open(x) 

    [snip] 

这做工作,但也不太令人满意。 听说有关产卵的东西吗?

+1

你的问题是相当模糊。你究竟想要达到什么目的?你觉得这种方法有什么不好的地方?是“我需要用户输入一些文本并将该文本作为字符串”?是“我需要用户编辑一个预先存在的文件”?你在问如何产生一个新的编辑器进程或如何从用户那里获得输入? – RarrRarrRarr 2010-04-05 05:34:41

+0

我正在讨论来自用户的输入。 :)我承认丑陋不是正确的词......也许是说,我正在寻找一个更优雅的方式来做这件事(如果有的话)。 – 2010-04-05 22:05:20

回答

2

我推荐使用的列表,而不是一个字符串:

def _get_content(editor, initial=""): 
    from subprocess import call 
    from tempfile import NamedTemporaryFile 

    # Create the initial temporary file. 
    with NamedTemporaryFile(delete=False) as tf: 
     tfName = tf.name 
     tf.write(initial) 

    # Fire up the editor. 
    if call([editor, tfName]) != 0: 
     return None # Editor died or was killed. 

    # Get the modified content. 
    with open(tfName).readlines() as result: 
     os.remove(tfName) 
     return result 
+0

谢谢迈克。这是个好主意。 – 2010-04-06 21:25:28

+1

Gah,忘记了理由:你想使用一个列表来调用''和'shell = False',因为这样你就不必担心转义文件名中的任何字符(空格,'&', ';'等)壳赋予特殊的含义。当然,NamedTemporaryFile不应该为这些字符提供一个文件名,但是这是一个很好的习惯。 – 2010-04-06 21:59:53

+0

谢谢你的提示! – 2010-04-08 00:53:58

3

这是所有程序都这么做的方式,AFAIK。当然,我使用的所有版本控制系统都会创建一个临时文件,并将其传递给编辑器,并在编辑器退出时检索结果,就像您一样。

+0

提到临时文件是好的..我在那个名为'tempfile'上找到了一个好的Python模块。我认为这听起来很棒。 – 2010-04-05 22:06:58

1

编辑器只是让你交互地编辑一个文件。你也可以用Python编辑文件。没有必要调用外部编辑器。

for line in open("file"): 
    print "editing line ", line 
    # eg replace strings 
    line = line.replace("somestring","somenewstring") 
    print line 
+0

是的,我知道。虽然我需要获得用户输入,然后立即处理这些数据,然后将其全部存储在数据库中,否则我会这样做。 :) – 2010-04-05 22:15:25