python - 使用我们可以编辑的外部 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
以便我可以更改角色名称?
解决方案
我能够找到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
记事本,编辑名称,安全,运行,并且名称按预期更新。
如果有更好的方法,我很想学习。
推荐阅读
- c - 从 hcf 函数获取控制到达非 void 函数的末尾
- java - Apache Camel:如何在 from 之后动态插入数据?
- asp.net-core - 提取身份验证方法时出现 401 未经授权的错误
- php - 验证表单提交时,允许任何字符
- reactjs - 反应路由器不会在路由更改时渲染组件
- angular - 如何在 msal-angular 配置中使用 forceRefresh: true?
- pandas - 如何将值插入另一个表的列中?
- elasticsearch - 什么是常量分数
- angular - 如何将 asp.net core(后端)和 angular 8(前端)应用程序一起部署到 Google App Engine?
- android - 由于错误,无法更新 Firestore 中的数组