从外部程序获取数据

1 投票
3 回答
2783 浏览
提问于 2025-04-15 21:14

我需要一个方法来从外部编辑器获取数据。

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]

我个人觉得应该有更优雅的解决办法。你看,我需要和一个外部编辑器互动,然后获取数据。

你知道有什么更好的方法或者想法吗?

编辑:

Marcelo 给我提了个建议,使用 tempfile 来实现这个功能。

这是我现在的做法:

def _tempfile_write(input):
    from tempfile import NamedTemporaryFile

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

    [snip]

这样可以完成任务,但我还是觉得不太满意。听说过什么是生成进程吗?

3 个回答

1

一个编辑器就是让你可以互动地编辑文件。你也可以用Python来编辑文件,其实不需要去调用外部的编辑器。

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

我知道的所有程序都是这样做的。肯定我用过的所有版本控制系统都会创建一个临时文件,把它交给编辑器,然后在编辑器关闭时获取结果,就像你所做的那样。

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

撰写回答