call up an EDITOR (vim) from a python script

后端 未结 5 1523
故里飘歌
故里飘歌 2020-12-01 00:19

I want to call up an editor in a python script to solicit input from the user, much like crontab e or git commit does.

Here\'s a snippet fr

5条回答
  •  悲&欢浪女
    2020-12-01 00:41

    In python3: 'str' does not support the buffer interface

    $ python3 editor.py
    Traceback (most recent call last):
      File "editor.py", line 9, in 
        tf.write(initial_message)
      File "/usr/lib/python3.4/tempfile.py", line 399, in func_wrapper
        return func(*args, **kwargs)
    TypeError: 'str' does not support the buffer interface
    

    For python3, use initial_message = b"" to declare the buffered string.

    Then use edited_message.decode("utf-8") to decode the buffer into a string.

    import sys, tempfile, os
    from subprocess import call
    
    EDITOR = os.environ.get('EDITOR','vim') #that easy!
    
    initial_message = b"" # if you want to set up the file somehow
    
    with tempfile.NamedTemporaryFile(suffix=".tmp") as tf:
        tf.write(initial_message)
        tf.flush()
        call([EDITOR, tf.name])
    
        # do the parsing with `tf` using regular File operations.
        # for instance:
        tf.seek(0)
        edited_message = tf.read()
        print (edited_message.decode("utf-8"))
    

    Result:

    $ python3 editor.py
    look a string
    

提交回复
热议问题