2013-07-23 42 views
0

如何在變量中包含外部配置文件並在python腳本中使用它們?Python 3包含帶變量的自定義文件

Python的變量文件:(auth.txt)

Username = 'username_here' 
Password = 'password_here' 

的Python腳本(test.py)

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

重命名'auth.txt'到'auth.py'和'import'它。 – Blender

+0

其實我把它重命名爲auth.py,然後使用auth import *還有其他方法可以做到這一點嗎? – Tux

回答

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) 
2

configparser會讓你把它像一本字典:

的config.txt

[DEFAULT] 
USR = user_here 
PWD = pass_here 

權威性。 py:

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

收率:

user_here 
pass_here 
+0

這是最簡單的解決方案。還有其他人,例如'xml.etree.ElementTree'如果你需要使用XML文件,但是爲了你的目的''configparser'以熟悉的語法完成你想要的任何事情。 – Kudzu

+0

是的,我更喜歡自己的回答。我不喜歡使用ini風格的配置,特別是如果它需要額外的模塊。但是,謝謝。 – Tux