【问题标题】:Is it possible to open a file in a window for the user to edit in Python? [closed]是否可以在窗口中打开文件供用户在 Python 中编辑? [关闭]
【发布时间】:2023-01-13 23:50:34
【问题描述】:

我想要一个在单独窗口中打开的文本文件,以便用户可以编辑其中的文本,当他们关闭它时,程序将读取该文件。这可能吗?

我试过用谷歌搜索这个,但我发现的只是如何打开 .py 文件或如何使用 open() 函数让程序自动编辑文件。

【问题讨论】:

  • 在一个单独的窗口中?你可以有一个 python 脚本作为一个服务运行,它不断地监视文件的修改日期,所以当用户打开、修改和保存文件时,可以触发一个脚本来读取文件
  • 您要使用哪个操作系统?
  • 你可以G。使用“os.system”或“subprocess.run”运行文本编辑器。

标签: python


【解决方案1】:

那么,你可以做的是以下,使用supprocess

import subprocess

subprocess.call(["code", "/your/file/full-path/example.txt", "--wait"])

# This will be executed once the program terminates,
# so when the user closes the window (or the tab, in this case,
# since we are using  VS Code)

print("done")

在此示例中,我使用了 VS Code,code 命令和 --wait 参数;如果您使用的是 Windows 操作系统,则可以将 code 替换为 notepad(或任何文本编辑器)并删除 --wait

请注意,print() 在程序关闭后执行。在您的情况下,subprocess.call() 执行完成后,您的文件已更新(除非用户决定不保存文件)。

您可以在这里找到其他示例:https://www.cyberciti.biz/faq/python-run-external-command-and-get-output/

【讨论】:

  • 您可以在 Mac 上使用open,在 Linux 上使用xdg-open(至少对于 xfce4),而不是对应用程序进行硬编码。 Windows 可能有也可能没有类似的东西。
  • 是的,这很有意义,但不确定问题是否假设我们要打开一个特定的应用程序,我认为open 启动系统定义的一个,根据给定文件扩展名的默认应用程序,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-09
相关资源
最近更新 更多