分享一個,python處理系統返回的內容,通過各種資料型別之間轉換,找到輸出想要欄位的小程式碼,我覺得對於學習資料型別挺有用的。

star_Zz發表於2020-12-06

達到輸入引數:小紅,就輸出小紅性別,輸入引數小明,就輸出小明性別的效果,

通過元組,列表,字典,字串之間的轉換,用於處理可能遇到大文字字串篩選

 ⚡ root@star  ~/python  cat shujuleixing.py
#!/usr/bin/python3
#coding=utf-8
import os
import subprocess
import sys

name=sys.argv[1]
cmd="cat /root/python/class.txt"
g=[]
def out_put(cmd):
    p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding='utf-8')
    stdout=p.communicate()
    return stdout
def step1(cmd):
    a=out_put(cmd)
    b=a[0]
    c=eval(b)
    for d in c:
        e=d['class']
        f=eval(e)
        g.append(f)
    print('a---',type(a),a)
    print('b---',type(b),b)
    print('c---',type(c),c)
    print('d---',type(d),d)
    print('e---',type(e),e)
    print('f---',type(f),f)
    print('g---',type(g),g)
def step2(cmd):
    step1(cmd)
    for h in g:
        if name==h['name']:
            i=h['sex']
        elif name==h['name']:
            i=h['sex']
    print('h---',type(h),h)
    print('i---',type(i),i)
step2(cmd)
 ⚡ root@star  ~/python cat class.txt
[{"class":"{\"name\":\"xiaoming\",\"sex\":\"male\"}"},{"class":"{\"name\":\"xiaohong\",\"sex\":\"female\"}"}]
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章