Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 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 Answer

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}')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...