加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如何从命令行程序调用文本编辑器,如git?

发布时间:2020-12-20 13:45:03 所属栏目:Python 来源:网络整理
导读:一些git命令,例如git commit,调用预先填充了一些值的基于命令行的文本编辑器(如 vim或nano或其他),并在用户保存并存在后,对保存的文件执行某些操作. 我应该如何在Linux上将此功能添加到Python类似的命令行程序中? 如果它不使用Python,请不要因为给出答案而
一些git命令,例如git commit,调用预先填充了一些值的基于命令行的文本编辑器(如 vim或nano或其他),并在用户保存并存在后,对保存的文件执行某些操作.

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

如果它不使用Python,请不要因为给出答案而停止自己,我会对一般的抽象答案感到满意,或者作为另一种语言的代码答案.

解决方法

解决方案取决于您拥有的编辑器,编辑器可能找到的环境变量以及编辑器是否采用任何命令行参数.

这是一个简单的解决方案,适用于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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读