开发者

Getting data from external program

开发者 https://www.devze.com 2022-12-25 11:28 出处:网络
I need a method to get the data from an external editor. def _get_content(): from subprocess import call

I need a method to get the data from an external editor.

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]

I personally think there should be a more elegant way. You see, I need to interact with an external editor and get the data.

Do you know any better approaches/have better ideas?

EDIT:

Marcelo brought me on the idea of using tempfile for doing that.

Here's how I do it:

def _tempfile_write(input):
    from tempfile import NamedTemporaryFile

    x = NamedTemporaryFile()
    x.file.write(input)
   开发者_如何学Go x.close()
    y = open(x)

    [snip]

This does the job, but also not quite satisfying. Heard something about spawning?..


This is the way all programs do it, AFAIK. Certainly all version control systems that I've used create a temporary file, pass it to the editor and retrieve the result when the editor exits, just as you have.


I'd recommend using a list, not a string:

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


an editor just lets you edit a file interactively. you can also edit files with Python. there's no need to call external editor.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号