实用的脚步通常需要一些动态参数,如果参数太多,从命令行传递就太麻烦了。
从配置文件读取,是比较实用的方法。
以下示例为从 test.cfg 中读取参数,配置文件为json格式。
配置文件内容如下:
{
"username":"root",
"password":"Admin@123",
"database":"test_db",
"tablename":"tb_01"
}
示例代码如下:
import json
import sys
pversion = int(sys.version[0:1])
def get_param(cfgfile):
global username
global password
global database
global tablename
if pversion<3:
with open(cfgfile) as j:
cfginfo=json.load(j)
j.close()
else:
with open(cfgfile,encoding="utf-8") as j:
cfginfo=json.load(j)
j.close()
username = cfginfo.get("username")
password = cfginfo.get("password")
database = cfginfo.get("database")
tablename = cfginfo.get("tablename")
if __name__ == '__main__':
cfgfile = 'test.cfg'
get_param(cfgfile)
print("Username:",username)
print("Password:",password)
print("Database:",database)
print("Tablename:",tablename)
[root@test1 dataC]# python2 test.py
('Username:', u'root')
('Password:', u'Admin@123')
('Database:', u'test_db')
('Tablename:', u'tb_01')
[root@test1 dataC]# python3 test.py
Username: root
Password: Admin@123
Database: test_db
Tablename: tb_01