Python 3包含带变量的自定义文件

时间:2013-07-23 23:29:33

标签: python variables printing

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

Python变量文件:(auth.txt)

Username = 'username_here'
Password = 'password_here'

Python脚本(test.py)

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

我用它来获得它;

auth.py

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

test.py

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