How to use a string as a variable name in Python

Source: Internet
Author: User
Tags string format vars python script

Application Scenario Description:

Get the service name configured on the server and run the port number through the configuration file, and write the Python script to detect if the service is running on the service?

#!/usr/bin/env python#-*-coding:utf-8-*-
# filename:config.py# Service Configuration class config: servicelist = ' Service1,service2,service3 ' Service1 = ' Service 1 ' Service1port = 8001 service2 = ' Service 2 ' service2port = 8002 service3 = ' Service 3 ' Service3port = 8003
#!/usr/bin/env python#-*-coding:utf-8-*-
# fileName:envCheck.pyimport socketfrom config Import configconfig = Configservicelist = config.servicelist# Determine if a port service is running def Portcheck (host, port): SK = Socket.socket (socket.af_inet, socket. SOCK_STREAM) sk.settimeout (1) try:sk.connect ((host, Port)) # print ' Service for port%d on server%s is running! '% (hos T, Port) return True except Exception: # print ' Services on server%s service port%d not running! '% (host, port) return Fa LSE Sk.close () # Basic service Run State Detection Def envcheck (): For ServiceName in Servicelist.split (', '): host = ' 127.0.0.1 ' # must As a string format, such as: ' 127.0.0.1 'serviceport = ". Join ([' Config. ', serviceName, ' Port ']) port = eval (serviceport) # ports must be numericIf Portcheck (host, port): Print U "%s service with service port%s on%s server is running ..."% (host, port, ServiceName) Else: Print U "%s service with service port%s on%s server not running!"% (host, port, serviceName) If __name__ = = "__main__": Envcheck ()

This is used to get the service port from the configuration using the string as the variable name, and here's how we can do it in addition to that.

A total of three implementation methods:

#method One:>> Serviceport ="'. Join (['CONFIG.', ServiceName,'Port'])>>port =locals () [Serviceport)]>>Print "%s:%d"%(ServiceName, Port)#Output Resultsservice1port:8001Service2port:8002Service3port:8003#Method Two:>> Serviceport ="'. Join (['CONFIG.', ServiceName,'Port'])>>port =VARs () [Serviceport)]>>Print "%s:%d"%(ServiceName, Port)#Output Resultsservice1port:8001Service2port:8002Service3port:8003#Method Three:>> Serviceport ="'. Join (['CONFIG.', ServiceName,'Port'])>>port =eval (serviceport)>>Print "%s:%d"%(ServiceName, Port)#Output Resultsservice1port:8001Service2port:8002Service3port:8003

1. Locals ()

Locals is a built-in function of Python, and he can access local and global variables in a dictionary way.

Python uses namespaces to record variables, like JavaScript's window, which records various global variables.

Each module, each function has its own namespace, which records the names and values of variables, constants, and classes.

Just like JS, when Python uses variables, it follows these steps to search:

    • A local variable of a function or class.
    • Global variables.
    • Built-in variables.

The above three steps, one of the steps to find the corresponding variable, will not look down. If none of the three steps are found, an exception is thrown.

The difference between locals and globals

    • Locals () is read-only. Globals () is not. Read-only, the value is read-only for the original variable. You can actually assign a value to locals ().
    • Globals returns a global variable for the current module locals returns a local variable. Note that locals returns a copy of the local variable that currently resides in the smallest namespace.
Physical examination Locals
List1 = [locals]  ()    #  in the global use of locals, will print List1 and __builtins__, __name__, __doc__, __ package__   Copy Code   def  foo (args):      x=1      print  Locals ()    foo (123)    # will get {' arg ': 123, ' X ': 1}  

2. VARs ()

This function is a Dictionary object that implements the property and property values of the object that is returned. If you do not enter parameters by default, the properties and property values of the current call location are printed, equivalent to the functionality of locals (). If there is a parameter input, only the corresponding property and property values of this parameter are printed.

# VARs ()        Print (VARs ())         class Foo:         = 1    print(VARs (foo))        = Foo ()    print(VARs (foo))   

3. Eval ()

The eval () function is powerful, as the official demo interprets the string str as a valid expression to evaluate and return the result of the calculation.

It works well with math as a calculator.

For other uses, you can convert list,tuple,dict and string to each other. See the following example:

A ="[ [up], [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="([up], [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 are at the cost. Security is one of its biggest drawbacks.

Think about this use environment: users are required to enter an expression and evaluate it.

If the user maliciously enters, for example:

__import__ (' OS '). System (' dir ')

Then eval (), you will find that the current directory files are now in front of the user.

Then continue typing:

Open (' File name '). Read ()

The code is given to people. Get finished, a delete command, the file disappears. Let's cry!

How to avoid security problems?

(1) Self-written check function;

(2) using Ast.literal_eval

How to use a string as a variable name in Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.