Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
99 views
in Technique[技术] by (71.8m points)

python - Python3 script for print command out put


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
import subprocess
'''
~/USR$ ps -a
    PID TTY          TIME CMD
1697 tty2     00:00:20 Xorg
1753 tty2     00:00:00 gnome-session-b
2474 pts/0    00:00:04 python3
2476 pts/0    00:00:00 python3
4038 pts/3    00:00:00 ps

'''
#your command: flow-cat /var/log/DataFlow////tmp | flow-stat -f9 -S1 | head -n 50 goes here
#my_cmd = "ps -a" in terminal but for subprocess split it like ['ps', '-a']

my_cmd = ['ps', '-a']
subprocess = subprocess.Popen(my_cmd, stdout=subprocess.PIPE) 
output, error = subprocess.communicate()

#choose what you want or decide runtime from requirement 
my_target_in_CMD  = 'gnome-session-b' 

#parse my_cmd output 
for line in output.splitlines():
    _mx_split = len(line.split())
    _pid = (line.split(None, _mx_split)[0]).decode('utf-8')
    _tty = (line.split(None, _mx_split)[1]).decode('utf-8')
    _time = (line.split(None, _mx_split)[2]).decode('utf-8')
    _cmd = (line.split(None, _mx_split)[3]).decode('utf-8')

    #logical decision 
    if _cmd == my_target_in_CMD:
        print(f'{_pid} : {_tty} : {_time} : {_cmd} <---- my_target_in_CMD')
    else:
        print(f'{_pid} : {_tty} : {_time} : {_cmd}')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...