从 Python CLI 程序内部智能启动默认编辑器?

发布于 2024-08-13 21:30:10 字数 196 浏览 1 评论 0原文

这个问题中的答案并没有触及问题的核心。在基于 CLI 的 Python 程序中,我希望用户能够编辑文件,然后返回到程序。在返回之前,我希望他们能够取消编辑。这应该类似于 Subversion 中的提交注释编辑功能。

目前此类任务的最佳实践是什么?

The answers in this question didn't get to the heart of the problem. In a CLI-based Python program, I want the user to be able to edit a file and then return to the program. Before returning, I want them to be able to cancel their edits. This should feel like the commit-note-editing feature in Subversion.

What are the current best practices for this type of task?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦在深巷 2024-08-20 21:30:11

您可以尝试查看 Mercurial 的源代码,它是用 Python 编写的。

他们使用 os.environ 来读取环境变量 HGEDITOR 、 VISUAL 和 EDITOR 的值,默认为 vi 。然后,他们使用 os.system 在使用 tempfile.mkstemp 创建的临时文件上启动编辑器。当编辑完成后,他们读取文件。如果其中有任何真实内容,则操作继续,否则中止。

如果您想了解 Mercurial 是如何实现的,详细信息请参见 ui .pyutil.py

You could try looking through the sources to Mercurial, which is written in Python.

They use os.environ to read the value of environment variables HGEDITOR, VISUAL, and EDITOR, defaulting to vi. Then they use os.system to launch the editor on a temp file created with tempfile.mkstemp. When the editor is done, they read the file. If it has any real content in it, the operation continues, otherwise, it is aborted.

If you want to see how Mercurial does it, the details are in ui.py and util.py.

阪姬 2024-08-20 21:30:11

Subversion 等使用 $EDITOR 环境变量来确定使用哪个程序来编辑文本文件。当然,$EDITOR 仅当您在 shell 中的 unixy 平台上时才起作用。对于 Windows(cmd /c start tempfile.txt)或 Mac OS X(open tempfile.txt),您必须执行不同的操作。

但是,这基本上就是您其他问题的答案和相关答案所说的。

如果您只想能够“取消”编辑,请制作文件的临时副本,然后调用编辑器。然后,您的程序可以将临时文件的内容复制到真实文件中,或者如果用户取消,则不复制。 Subversion 基本上就是这样做的。

Subversion, et al use the $EDITOR environment variable to determine which program to use to edit text files. Of course, $EDITOR will only work if you're on a unixy platform in a shell. You'll have to do something different for Windows (cmd /c start tempfile.txt) or Mac OS X (open tempfile.txt).

But, this is essentially what the answers and related answers to your other question said.

If you just want to be able to "cancel" edits, then make a temporary copy of the file, and invoke your editor on that. Your program can then copy the contents of the temporary file into the real file or, if the user cancels, don't. This is basically how Subversion does it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文