python填坑(1)

return

执行到return语句时,会退出函数,return之后的语句不再执行。。。但将return语句放在try语句块中,是个例外。。。。

def fun():
    print(kk)
    return 'ok'#执行到该return语句时,函数终止,后边的语句不再执行
    print(kk)
 
def func():
    try:
        print(kk)
        return 'ok' #函数得到了一个返回值
    finally:#finally语句块中的语句依然会执行
        print(kk)
 
print fun()
print '----------'
print func()

运行结果:

kk
ok
----------
kk
kk
ok

判断列表为空

直接 if a 就是判断在列表不为空的时候,需要执行的命令
即使用’in’之前要保证record不是’None’

a = []
if a:
 COMMAND

TypeError: argument of type ‘NoneType’ is not iterable

                    if casess.metric in endpoint_all_ok_metric_list:
                        pass
                    else:
                        endpoint_all_ok_metric_list.append(casess.metric)

#报错,TypeError: argument of type ‘NoneType’ is not iterable
是因为 用’in’之前要保证list不是’None’
所以,修改了下。

                if endpoint_all_ok_metric_list:
                    if casess.metric in endpoint_all_ok_metric_list:
                        pass
                    else:
                        endpoint_all_ok_metric_list.append(casess.metric)
                else:
                    endpoint_all_ok_metric_list.append(casess.metric) 

TypeError: not enough arguments for format string

最近在学Python,语句:

'user %s,id:%s'  %  self.__name, self.__id
报了个错误

Python TypeError: not enough arguments for format string
一看就傻眼了,参数不够?明明是给够两个了啊

后来google发现,后面给的参数要是元组的形式,即:

'user %s,id:%s'  %  (self.__name, self.__id)
才是对的

str去除两边空格

str.strip()

Linux 如何显示一个文件的某几行

  1. 从第1000行开始,显示2000行。即显示1000~2999行

cat input_file | tail -n +1000 | head -n 2000

tail -n 4000 /home/work/open-falcon/agent/logs/agent.log |grep gpu.alive|head
## 直接tail -n 140000 这样数量太大。 先用cat ,在tail就会好一些.

root@hypereal-System-Product-Name:/home/hypereal# cat /home/work/open-falcon/agent/logs/agent.log |tail -n 13000|wc -l
13000

查看时间间隔内的 日志。

cat /home/work/open-falcon/agent/logs/agent.log|sed -n '/2019\/01\/09 08*/,/2019\/01\/09 09*/p'|grep gpu.alive|grep -v "Value:17"
xxx@xxx:~$ cat /home/work/open-falcon/agent/logs/agent.log|sed -n '/2019\/01\/09 08*/,/2019\/01\/09 09*/p'|grep gpu.alive|grep -v "Value:17"
2019年 01月 09日 星期三 08:17:54 CST:2019/01/09 08:17:54 var.go:88: => <Total=1> <Endpoint:dm/70-85-c2-84-53-a6, Metric:gpu.alive, Type:GAUGE, Tags:cluster=detection-machine,cluster=detection-machine, Step:60, Time:1546993075, Value:3>
2019年 01月 09日 星期三 08:18:55 CST:2019/01/09 08:18:55 var.go:88: => <Total=1> <Endpoint:dm/70-85-c2-84-53-a6, Metric:gpu.alive, Type:GAUGE, Tags:cluster=detection-machine,cluster=detection-machine, Step:60, Time:1546993135, Value:3>
2019年 01月 09日 星期三 08:19:55 CST:2019/01/09 08:19:55 var.go:88: => <Total=1> <Endpoint:dm/70-85-c2-84-53-a6, Metric:gpu.alive, Type:GAUGE, Tags:cluster=detection-machine,cluster=detection-machine, Step:60, Time:1546993195, Value:3>
2019年 01月 09日 星期三 08:53:33 CST:2019/01/09 08:53:33 var.go:88: => <Total=1> <Endpoint:dm/70-85-c2-84-53-a6, Metric:gpu.alive, Type:GAUGE, Tags:cluster=detection-machine,cluster=detection-machine, Step:60, Time:1546995214, Value:3>
2019年 01月 09日 星期三 08:54:33 CST:2019/01/09 08:54:33 var.go:88: => <Total=1> <Endpoint:dm/70-85-c2-84-53-a6, Metric:gpu.alive, Type:GAUGE, Tags:cluster=detection-machine,cluster=detection-machine, Step:60, Time:1546995274, Value:3>
2019年 01月 09日 星期三 08:55:34 CST:2019/01/09 08:55:34 var.go:88: => <Total=1> <Endpoint:dm/70-85-c2-84-53-a6, Metric:gpu.alive, Type:GAUGE, Tags:cluster=detection-machine,cluster=detection-machine, Step:60, Time:1546995334, Value:3>
xxx@xxx:~$ 

判断是否 数字,字母,
str_1 = "123"
str_2 = "Abc"
str_3 = "123Abc"

#用isdigit函数判断是否数字
print(str_1.isdigit())
Ture
print(str_2.isdigit())
False
print(str_3.isdigit())
False

#用isalpha判断是否字母
print(str_1.isalpha())    
False
print(str_2.isalpha())
Ture    
print(str_3.isalpha())    
False

#isalnum判断是否数字和字母的组合
print(str_1.isalnum())    
Ture
print(str_2.isalnum())
Ture
print(str_1.isalnum())    
Ture
注意:如果字符串中含有除了字母或者数字之外的字符,比如空格,也会返回False
一个修改terminal 名称的脚本
import requests
from misc import *
import netifaces
import subprocess
import os
import shutil

if os.path.exists('/etc/url'):
    with open("/etc/url","r") as env:
        for line in env:
            if 'WEB_SERVER' in line:
                server_url=line.replace("WEB_SERVER=","").strip()
            else:
                server_url="https://www.xxx.com"
else:
    server_url="https://www.xxx.com"

machineId = getMachineId() or "ErrorUnknown"
r = requests.get(server_url + "/Alias/{}".format(machineId))
alias = r.json()['alias']

for interface in sorted(netifaces.interfaces()):
    if interface.startswith("en") or interface.startswith("eth"):
        mac = netifaces.ifaddresses(interface)[netifaces.AF_LINK][0]['addr']
        mac = mac.replace(":","-")

alias=alias +'(' + mac + ')'

if os.path.exists('/root/.bashrc-bak'):
    pass
else:
    shutil.copyfile("/root/.bashrc","/root/.bashrc-bak")    ### copy 文件,
    
if os.path.exists('/home/hypereal/.bashrc-bak'):      ###判断文件
    pass
else:
    shutil.copyfile("/home/hypereal/.bashrc","/home/hypereal/.bashrc-bak")

shutil.copyfile("/root/.bashrc-bak","/root/.bashrc")                    ###复制文件
shutil.copyfile("/home/hypereal/.bashrc-bak","/home/hypereal/.bashrc")

cmd_root = "sed -i '/PS1=/ s/u@\\\h/u@"+alias+"/g'  /root/.bashrc"            ####sed中'\‘的匹配。   \\\      \
cmd_hypereal = "sed -i '/PS1=/ s/u@\\\h/u@"+alias+"/g'  /home/hypereal/.bashrc"    ###   \\\\$alias      \$alias
#cmd_root = "sed -i '/PS1=/ s/u@" + alias +"/u@\\\h/g'  /root/.bashrc"
#cmd_hypereal = "sed -i '/PS1=/ s/u@"+ alias +"/u@\\\h/g'  /home/hypereal/.bashrc"

status,tem = subprocess.getstatusoutput(cmd_root)
status,tem = subprocess.getstatusoutput(cmd_hypereal)
status,tem = subprocess.getstatusoutput("source /root/.bashrc")
status,tem = subprocess.getstatusoutput("source /home/hypereal/.bashrc")
“=” 是共用内存, 需要用copy.

在下面的例子中,关键就是这两句。

all_machine_info_online=all_machine_info
##    all_machine_info_online=copy.copy(all_machine_info)   ## 修改之后采用 copy.


all_machine_info_online.remove(machine_sigle_info)


可以看到。 for 循环用到了变量 , 原来len 得到650,但是循环只执行了了610次。
debug发现。
 但是在循环内 又 = 引用了变量, 所以直接导致变量改变, 选用copy之后就解决了这个问题,

for machine_sigle_info in all_machine_info:
        for_count+=1
        if machine_sigle_info['Id']:
            all_mac.append(machine_sigle_info['Id'])
            if machine_sigle_info['LastUpdate']:
                LastUpdate = str(machine_sigle_info['LastUpdate'])   ##        if the time between now and lastupdate is longer than 6 min,  we think it is offline.
                a=LastUpdate.replace('T'," ")[0:19]
                LastUpdate_unix = time.mktime(time.strptime(a,'%Y-%m-%d %H:%M:%S'))
                time_now_unix = time.time()
                time_long = time_now_unix - LastUpdate_unix
 
                all_machine_info_online=copy.copy(all_machine_info)         
               if time_long > 480.00 :
                    all_machine_info_online.remove(machine_sigle_info)
                    offline_count += 1
                    all_machine_info_offline_mac.append(machine_sigle_info['Id'])
                else:
                    all_machine_info_online_mac.append(machine_sigle_info['Id']) 
            else:
                macs_no_lastupdate.append(machine_sigle_info['Id'])
        else:
            all_mac_no_id.append(machine_sigle_info)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值