How Python strings as variable names

Description scenarios:

Gets the service name and port number configured to run on the server configuration file, write service is running on a python script testing services?

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# fileName: config.py
# 服务配置
class config:
    serviceList = 'service1,service2,service3'
    service1 = '服务1'
    service1Port = 8001
    service2 = '服务2'
    service2Port = 8002
    service3 = '服务3'
    service3Port = 8003

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# fileName: envCheck.py
import socket
from config import config

config = config
serviceList = config.serviceList

# 判断某端口服务是否运行
def portCheck(host, port):
    sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sk.settimeout(1)
    try:
        sk.connect((host, port))
        # print '在服务器 %s 上服务端口 %d 的服务正在运行!' % (host, port)
        return True
    except Exception:
        # print '在服务器 %s 上服务端口 %d 的服务未运行!' % (host, port)
        return False
    sk.close()

# 基础服务运行状态检测
def envCheck():
    for serviceName in serviceList.split(','):
        host = '127.0.0.1'  # 必须为字符串格式,如:'127.0.0.1'
        servicePort = ''.join(['config.',serviceName,'Port'])
        port = eval(servicePort)  # 端口必须为数字
        if portCheck(host, port):
            print u"在%s服务器上服务端口为 %s 的 %s 服务正在运行......" % (host, port, serviceName)
        else:
            print u"在%s服务器上服务端口为 %s 的 %s 服务未运行!" % (host, port, serviceName)


if __name__ == "__main__":
    envCheck()

The use to which the string variable names as a way of obtaining service from the port configuration, let's look in addition to the specific ways in which this way there can be achieved

There are three methods to achieve:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
# 方法一:
>> servicePort = ''.join(['config.',serviceName,'Port'])
>>port = locals()[servicePort)] 
>>print "%s:%d" %(serviceName, port)
# 输出结果
service1Port:8001
service2Port:8002
service3Port:8003

# 方法二:
>> servicePort = ''.join(['config.',serviceName,'Port'])
>>port = vars()[servicePort)] 
>>print "%s:%d" %(serviceName, port)
# 输出结果
service1Port:8001
service2Port:8002
service3Port:8003

# 方法三:
>> servicePort = ''.join(['config.',serviceName,'Port'])
>>port = eval(servicePort) 
>>print "%s:%d" %(serviceName, port)
# 输出结果
service1Port:8001
service2Port:8002
service3Port:8003

1. locals()

locals is a python's built-in functions, he may be the dictionary way to access local and global variables.

python which records the variable name with a space, like a window javascript, like he recorded with a variety of global variables.

Each module, each function has its own namespace, a record of variables, constants, class names and values.

Like JS as, when python in the use of variables, will follow the steps below to search:

  • Local variables or the like.
  • Global variables.
  • Built-in variables.

The above three steps, one step to find the corresponding variable, it will not look down. If you can not find in these three steps, it will throw an exception.

The difference between locals and globals

  • locals () is read-only. globals () instead. Here that the read-only, read-only for the value of the original variable. In fact, you can also locals () assignment.
  • globals returns the global variable return current module is a local variable locals. Note that, locals returns a copy of the current location of the local variable minimum namespace.

Examination locals

list1 = [1,2,3]  
locals()  
  
# 在全局中使用locals,会打印出list1和__builtins__、__name__、__doc__、__package__  
复制代码  
def foo(args):  
    x=1  
    print locals()  
  
foo(123)  
  
#将会得到 {'arg':123,'x':1}

Whose 2. ()

This function is implemented to return the object attributes and attribute values ​​of the object dictionary. If the default is not an input parameter, print attributes and attribute values ​​of the current position of the calls, the equivalent of locals () function. If there is an input parameter, it is only the corresponding print attributes and values ​​of the parameters.

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
#vars()    
    
print(vars())    
    
class Foo:    
    a = 1    
print(vars(Foo))    
    
foo = Foo()    
print(vars(foo))

3. eval()

eval () function is very powerful, the official demo interpreted as: the string str as a valid expression to be evaluated and returns the results.

Combined math calculator as a good use.

Other usage can list, tuple, dict and string into each other. See below example:

a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"  
b = eval(a)  
b  
Out[3]: [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]  
type(b)  
Out[4]: list  
a = "{1: 'a', 2: 'b'}"  
b = eval(a)  
b  
Out[7]: {1: 'a', 2: 'b'}  
type(b)  
Out[8]: dict  
a = "([1,2], [3,4], [5,6], [7,8], (9,0))"  
b = eval(a)  
b  
Out[11]: ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))

Powerful functions come at a price. Security is its biggest drawback.

Think about this use of the environment: the need for the user to enter an expression, and evaluated.

If a malicious user input, for example:

__ import__('os').system('dir')

So after eval (), you will find the file in the current directory will be displayed in front of the user.

Then continue typing:

open('文件名').read()

Posters of the code. Acquisition is completed, a delete command, the file disappeared. Kuba!

How to avoid security problems?

(1) Write self inspection function;

(2) ast.literal_eval

Published 706 original articles · won praise 728 · views 1 million +

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/103937104