Python3包含带有变量的自定义文件

Python3包含带有变量的自定义文件,python,variables,printing,Python,Variables,Printing,如何包含带有变量的外部配置文件并在python脚本中使用它们 Python变量文件:(auth.txt) Python脚本(test.py) 我是用电脑得到的 auth.py # Python Variables USR = 'user_here' PWD = 'pass_here' test.py #!/bin/python -B from auth import * print('Username:', USR) print('Password:', PWD) configparser将

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

Python变量文件:(auth.txt)

Python脚本(test.py)

我是用电脑得到的

auth.py

# Python Variables
USR = 'user_here'
PWD = 'pass_here'
test.py

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

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

auth.txt
重命名为
auth.py
import
它。实际上,我是通过重命名为auth.py然后使用from auth import*获得它的。还有其他方法吗?这是最简单的解决方案。如果您需要使用xml文件,还可以使用其他文件,例如
xml.etree.ElementTree
,但出于您的目的,
configparser
可以用熟悉的语法执行所有您需要的操作。是的,我更喜欢我自己的答案。我不喜欢使用ini样式的配置,尤其是当它需要额外的模块时。但是谢谢。
import configparser
config = configparser.ConfigParser()
config.read('./config.txt')
print(config['DEFAULT']['USR'])
print(config['DEFAULT']['PWD'])
user_here
pass_here