【问题标题】:Python 3 Include Custom File with VariablesPython 3 包含带有变量的自定义文件
【发布时间】:2013-07-23 23:29:33
【问题描述】:

如何在外部配置文件中包含变量并在 python 脚本中使用它们?

Python 变量文件:(auth.txt)

Username = 'username_here'
Password = 'password_here'

Python 脚本 (test.py)

print('Username:', Username)
print('Password:', Password)

【问题讨论】:

  • auth.txt 重命名为 auth.pyimport
  • 实际上我是通过重命名为 auth.py 然后使用 from auth import * 得到的 * 还有其他方法吗?

标签: python variables printing


【解决方案1】:

configparser 会让你把它当作字典:

config.txt

[DEFAULT]
USR = user_here
PWD = pass_here

auth.py:

import configparser
config = configparser.ConfigParser()
config.read('./config.txt')
print(config['DEFAULT']['USR'])
print(config['DEFAULT']['PWD'])

产量:

user_here
pass_here

【讨论】:

  • 这是最简单的解决方案。还有其他的,例如xml.etree.ElementTree 如果您需要使用 XML 文件,但出于您的目的,configparser 会以熟悉的语法完成您想要的一切。
  • 是的,我更喜欢我自己的答案。我不喜欢使用 ini 风格的配置,特别是如果它需要额外的模块。不过谢谢。
【解决方案2】:

我通过使用得到它;

auth.py

# Python Variables
USR = 'user_here'
PWD = 'pass_here'

test.py

#!/bin/python -B
from auth import *
print('Username:', USR)
print('Password:', PWD)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    相关资源
    最近更新 更多