我如何像git一样从命令行程序调用文本编辑器?

问题描述 投票:4回答:1

某些git命令,例如git commit,调用基于命令行的文本编辑器(例如vimnano或其他),该文本编辑器预先填充了一些值,并且在用户保存并存在之后,对保存的文件进行操作。

我应该如何在Linux上继续将此功能添加到类似Python的命令行程序中?


[如果不使用Python,请不要停止给出答案,我将对通用的抽象答案或作为另一种语言的代码的答案感到非常满意。

python linux command-line-interface
1个回答
1
投票

解决方案将取决于您拥有的编辑器,可能在哪个环境变量中找到该编辑器,以及该编辑器是否使用任何命令行参数。

这是一个简单的解决方案,可在Windows上使用,而无需任何环境变量或编辑器的命令行参数。根据需要进行修改。

import subprocess
import os.path

def start_editor(editor,file_name):

    if not os.path.isfile(file_name): # If file doesn't exist, create it
        with open(file_name,'w'): 
            pass

    command_line=editor+' '+file_name # Add any desired command line args
    p = subprocess.Popen(command_line)
    p.wait()

file_name='test.txt' # Probably known from elsewhere
editor='notepad.exe' # Read from environment variable if desired

start_editor(editor,file_name)

with open(file_name,'r') as f: # Do something with the file, just an example here
    for line in f:
        print line

0
投票

click是一个很好的命令行处理库,它具有一些实用程序,click.edit()是可移植的,并使用EDITOR环境变量。我在编辑器中输入了stuff行。请注意,它以字符串形式返回。很好。

(venv) /tmp/editor $ export EDITOR='=mvim -f'
(venv) /tmp/editor $ python
>>> import click
>>> click.edit()
'stuff\n'

查看文档https://click.palletsprojects.com/en/7.x/utils/#launching-editors我的整体经验:

/tmp $ mkdir editor
/tmp $ cd editor
/tmp/editor $ python3 -m venv venv
/tmp/editor $ source venv/bin/activate
(venv) /tmp/editor $ pip install click
Collecting click
  Using cached https://files.pythonhosted.org/packages/fa/37/45185cb5abbc30d7257104c434fe0b07e5a195a6847506c074527aa599ec/Click-7.0-py2.py3-none-any.whl
Installing collected packages: click
Successfully installed click-7.0
You are using pip version 19.0.3, however version 19.3.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
(venv) /tmp/editor $ export EDITOR='=mvim -f'
(venv) /tmp/editor $ python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import click
>>> click.edit()
'stuff\n'
>>>
© www.soinside.com 2019 - 2024. All rights reserved.