【问题标题】:Python3 import variables from myfile.confPython3 从 myfile.conf 导入变量
【发布时间】:2014-08-17 19:56:54
【问题描述】:

我有一个python程序'gametree.py',我想在'gametree.conf'中预定义一些变量并将它们导入我的python程序。

如果我将其命名为anything.py,我可以很好地导入它们,但我不想将其命名为*.py。这是一个配置文件,我想将它与带有 .conf 扩展名的 python 程序名称匹配。

gametree.py & gametree.conf

可能吗?

【问题讨论】:

  • This answer 可能是您正在寻找的。您可以使用__file__ 变量访问脚本的名称。
  • 我不明白它是如何工作的。我想使用命令'import gametree.conf'......这不起作用。 'importanything.py' 会起作用,但这不是我想要的。 :-)
  • 不要使用import;使用open 并读取文件。使用 JSON 之类的东西来保存配置数据。
  • 我先尝试使用“open”。阅读单个变量似乎要困难得多。我必须解析它,然后我必须将数字数据(一些字符串)转换为整数。使用 open 比仅仅读取变量要多得多的工作。我很感激这个提议,你是对的,但我的问题仍然存在。有什么方法可以导入不以扩展名 .py 结尾的文件?

标签: variables python-3.x import


【解决方案1】:

是的,你想要 configparser 模块

这应该可以帮助您:

configexample.py

import configparser
# note that this is for python3. Some changes need to be made for python2

# create parser object and read config file
config = configparser.RawConfigParser()
config.read('myconfig.cfg')

# loop through. Here for instructional purposes we print, but you can 
# assign etc instead.
for section in config.sections():
    print(section)
    for option in config.options(section):
        text = '{} {}'.format(option, config.get(section,option))
        print(text)

代码中的部分提取括号[]的内容。这是一个示例配置文件myconfig.cfg

[auth]
username= Petra
password= topsecret
[database]
server= 192.168.1.34
port= 143
file='thatfile.dat'
[Location]
language = English
timezone = UTC

更多详情请查看documentation

附录:如果您有兴趣,也可以使用jsonshlex 模块。

【讨论】:

    猜你喜欢
    • 2018-11-18
    • 2012-08-23
    • 2020-07-17
    • 2013-11-07
    • 2023-03-06
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多