无法有条件地循环打印行

时间:2019-03-28 14:49:01

标签: python-3.x

需要有关此脚本的帮助,在该脚本中,我尝试获取与该命令相关的输出。例如,在下面的代码中     “与进程和输出有关的信息应该是ps -ef命令输出,并且应该同样继续执行下一个命令和print语句” 但是我说的是

  

与过程有关的信息,所有命令一次显示。

#!/usr/bin/env python3.7
import os
state = ['process' , 'http status' , 'date info' , 'system']
def comm(com):
    for i in state:
            for j in com:
                    print (f"info related to {i}")
                    os.system(j)

cmd = ['ps -ef | head -2' , 'systemctl status httpd' , 'date' , 'uptime']
comm(cmd)

输出:

info related to process
UID         PID   PPID  C STIME TTY          TIME CMD
root          1      0  0 10:13 ?        00:00:19 /usr/lib/systemd/systemd - 
-switched-root --system --deserialize 22
info related to process
● httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor 
preset: disabled)
Active: active (running) since Wed 2019-03-27 18:27:50 IST; 1 day 2h ago
 Docs: man:httpd(8)
       man:apachectl(8)
 Process: 8585 ExecReload=/usr/sbin/httpd $OPTIONS -k graceful (code=exited, 
status=0/SUCCESS)
Main PID: 1367 (httpd)
Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 
B/sec"
Tasks: 6
CGroup: /system.slice/httpd.service
       ├─1367 /usr/sbin/httpd -DFOREGROUND
       ├─8597 /usr/sbin/httpd -DFOREGROUND
       ├─8598 /usr/sbin/httpd -DFOREGROUND
       ├─8599 /usr/sbin/httpd -DFOREGROUND
       ├─8600 /usr/sbin/httpd -DFOREGROUND
       └─8601 /usr/sbin/httpd -DFOREGROUND

info related to process
Thu Mar 28 21:03:57 IST 2019
info related to process
21:03:57 up 10:50,  4 users,  load average: 0.35, 0.09, 0.14

1 个答案:

答案 0 :(得分:1)

您有两个循环,一个循环嵌套在另一个循环中。这意味着内部循环所做的任何事情都将在外部循环的每次迭代中执行。这就是循环的工作方式,但不是您想在这里执行的操作(我想)。

您有os模块要执行的命令以及与它们关联的几个状态名称。从数据优先的角度来看,我们可以将它们构造成字典:

commands = {
    'process': 'ps -ef',
    'http status': 'systemctl status httpd',
    'date info': 'date',
    'sytem': 'uptime',
}

现在,当我们遍历此字典时,在每次迭代中,我们都将有状态名称和要作为循环变量运行的命令。循环变成单个for循环,最后得到:

def comm(commands):
    for name, command in commands.items():
        print (f"info related to {name}")
        os.system(command)