首页 > 解决方案 > 使用我们可以编辑的外部 config.py 编译一个 python 应用程序

问题描述

我试图了解如何将config.py文件与非常基本的应用程序一起使用,该应用程序允许config.py文件位于已编译的 .exe 应用程序之外。

这是我的文件结构。

/ config.py

/ sayhello.py

[sayhello.py]

import config as config

if __name__ == "__main__":
    print (config.CHARACTERS['PLAYER_1'] + ", I'd like for you to meet " + config.CHARACTERS['PLAYER_2'] + ".")
    print (config.CHARACTERS['PLAYER_2'] + ", this is your cousin " + config.CHARACTERS['PLAYER_1'] + ".\n")

[配置.py]

# Define player names
CHARACTERS = {
    'PLAYER_1': "Abby",
    'PLAYER_2': "Billy"
}

我在 Visual Studio Code 中运行脚本,输出如下所示。

Abby, I'd like for you to meet Billy.
Billy, this is your cousin Abby.

我运行pyinstaller sayhello.py并且我有应用程序的构建/分布。我执行sayhello.exe并且输出如预期的那样,太棒了。

Abby, I'd like for you to meet Billy.
Billy, this is your cousin Abby.

我要编辑的文件在哪里,config.py以便我可以更改角色名称?

标签: pythonconfiguration

解决方案


我能够找到configparser并找到一个可行的解决方案。

[sayhello.py]

from configparser import ConfigParser

parser = ConfigParser()
parser.read('config.ini')

player_one = str(parser.get('CHARACTERS', 'PLAYER_1'))
player_two = str(parser.get('CHARACTERS', 'PLAYER_2'))

if __name__ == "__main__":
    print (player_one + ", I'd like for you to meet " + player_two + ".")
    print (player_two + ", this is your cousin " + player_one + ".\n")

[配置.ini]

[CHARACTERS]
PLAYER_1 = Abby
PLAYER_2 = Billy

我还发现auto-py-to-exe这使我能够将我的config.ini文件添加到我的构建中。该文件已重命名为config.py. 我能够打开config.py记事本,编辑名称,安全,运行,并且名称按预期更新。

如果有更好的方法,我很想学习。


推荐阅读