预约成功
应用场景描述:
通过配置文件获取服务器上配置的服务名及运行端口号,编写python脚本检测服务上服务是否在运行?
#!/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
#!/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()
这个里面使用到了将字符串作为变量名的方式从配置中获取服务端口,下面我们具体看下除了这种方式以外还有哪些方式可以实现。
一共有三种实现方法:
1、python字符串做变量名的方法有哪些——方法一:
>> servicePort = ''.join(['config.',serviceName,'Port'])
>>port = locals()[servicePort)]
>>print "%s:%d" %(serviceName, port)
# 输出结果
service1Port:8001
service2Port:8002
service3Port:8003
2、python字符串做变量名的方法有哪些——方法二:
>> servicePort = ''.join(['config.',serviceName,'Port'])
>>port = vars()[servicePort)]
>>print "%s:%d" %(serviceName, port)
# 输出结果
service1Port:8001
service2Port:8002
service3Port:8003
3、python字符串做变量名的方法有哪些——方法三:
>> servicePort = ''.join(['config.',serviceName,'Port'])
>>port = eval(servicePort)
>>print "%s:%d" %(serviceName, port)
# 输出结果
service1Port:8001
service2Port:8002
service3Port:8003
以上就是《python字符串做变量名的方法有哪些?这些方法对python应用很重要》的全部内容,这些python的使用技巧,全部都要建立在正确无误的代码上,环球网校的小编也祝大家python学习之路顺利。如果你想知道更多的python编程知识,可以点击下方资料下载链接。