Python 变量的变量

最近在写一个程序的过程中,遇到一个 Python 变量的变量的问题,就是某个变量的值,还是变量,然后我想取最终的值,感谢伟大的 google,写这篇文章记录下。先上代码:

#!/usr/bin/env python
#encoding=utf-8

import inspect
import ConfigParser

confPath="/home/test/config/config"

def modify_config(domain_name, app_type, port, if_api, vip, svn, svnver, yfb_ip, cron_ip, hosts, hostname, if_cas_oa, if_session, if_nginx, check_apps_dir, health_check):
    if vip is None:
        vip=""
    if yfb_ip is None:
        yfb_ip=""
    if cron_ip is None:
        cron_ip=""
    if hosts is None:
        hosts=""
    if if_cas_oa is None:
        if_cas_oa=""
    if if_session is None:
        if_session=""
    # 更新指定section, option的值
    conf = ConfigParser.ConfigParser()
    conf.read(confPath)
    ### 这个 inspect.getargspec 的作用是取函数的参数列表
    arg_list = inspect.getargspec(modify_config).args
    ### 下面的 conf.set 的第二个参数我只想取 arg 的值,而 第三个参数想取 arg 变量值的值,因为 arg 的值本身就是 modify_config 函数的参数
    for arg in arg_list:
        conf.set("online", arg, locals().get(arg))
    conf.write(open(confPath,"w"))

if __name__ == '__main__':
    domain_name = "www.test.com" 
    app_type = "osp" 
    port = "8081"
    if_api = "1" 
    vip = "192.168.0.1" 
    svn = "https://svn.tools.test.com/svn/" 
    svnver = "24562"
    yfb_ip = "192.168.0.1"
    cron_ip = "192.168.0.2"
    hosts = "www.test.com"
    hostname = "JD-TEST-COM"
    if_cas_oa = "0"
    if_session = "mcs2"
    if_nginx = "1"
    check_apps_dir = "0"
    health_check = "_health_check"
    modify_config(domain_name, app_type, port, if_api, vip, svn, svnver, yfb_ip, cron_ip, hosts, hostname, if_cas_oa, if_session, if_nginx, check_apps_dir, health_check)

参考资料

http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python

    原文作者:yexiaobai
    原文地址: https://segmentfault.com/a/1190000003499227
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞