从 Python CLI 程序内部智能启动默认编辑器?
这个问题中的答案并没有触及问题的核心。在基于 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试查看 Mercurial 的源代码,它是用 Python 编写的。
他们使用 os.environ 来读取环境变量 HGEDITOR 、 VISUAL 和 EDITOR 的值,默认为 vi 。然后,他们使用
os.system
在使用tempfile.mkstemp
创建的临时文件上启动编辑器。当编辑完成后,他们读取文件。如果其中有任何真实内容,则操作继续,否则中止。如果您想了解 Mercurial 是如何实现的,详细信息请参见 ui .py 和 util.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 variablesHGEDITOR
,VISUAL
, andEDITOR
, defaulting to vi. Then they useos.system
to launch the editor on a temp file created withtempfile.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.
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.