Python 应用程序菜单

Python application menu

我正在 Python 中为我正在创建的 linux 桌面环境编写应用程序菜单,我想知道是否有允许我读取 .desktop 的模块文件,并根据结果创建 Dict/Object。

如果没有,我想要一些关于如何自己编写此内容的提示。

使用内置的 open() 函数并设置读取参数。如果您在使用该函数时遇到问题,请考虑查看 python 参考 Python Library Reference, open() function。在那里您会找到有关如何使用该函数及其参数的全面说明。 Youtube 和 Google 还将为您提供足够的关于如何读取和写入 python.

中的文件的教程。

希望这能解决您的问题。

您所指的文件(.desktop 文件)的结构类似于许多应用程序的 .ini 文件,如 this example on the Arch Linux Wiki:

中所示
[Desktop Entry]
Type=Application                          # Indicates the type as listed above
Version=1.0                               # The version of the desktop entry specification to which this file complies
Name=jMemorize                            # The name of the application
Comment=Flash card based learning tool    # A comment which can/will be used as a tooltip
Exec=jmemorize                            # The executable of the application.
Icon=jmemorize                            # The name of the icon that will be used to display this entry
Terminal=false                            # Describes whether this application needs to be run in a terminal or not
Categories=Education;Languages;Java;      # Describes the categories in which this entry should be shown

章节以[Bracketed Text]开头,其他都是key-value对,由=分隔(我也看过:)。

Python 有 built-in ConfigParser module to handle these. That link is the technical documentation but the PythonWiki has a page with simpler examples。该库完全按照您的要求进行操作:它将格式类似于 .desktop 文件的文件读取到 objects 和字典中。

wiki 上的第一个示例清楚地说明了这一点:

>>> import ConfigParser
>>> Config = ConfigParser.ConfigParser()
>>> Config
<ConfigParser.ConfigParser instance at 0x00BA9B20>
>>> Config.read("c:\tomorrow.ini")
['c:\tomorrow.ini']
>>> Config.sections()
['Others', 'SectionThree', 'SectionOne', 'SectionTwo']

我们导入ConfigParser(在Python3中重命名为configparser),实例化它,并告诉它读取文件。 Config.sections() 现在是包含所有部分的列表 headers [Bracketed Text].

根据您的需要,ConfigParser object 有多种风格。基本的方法有getintgetboolean等方法,它们接受一个部分和一个选项并尝试return将其强制转换为指定的Pythonobject.还有像 itemsdefaults 这样的方法 return 项目和默认值分别来自作为参数给出的部分。

我个人对 .desktop 文件了解不多,无法知道您可能会遇到什么样的事情,或者您需要如何配置解析器,但这应该可以帮助您入门。