使用.format Python 2.6.6将第二条shell输出行的数据添加到另一个shell输入命令中需要的工具

2024-10-02 20:32:29 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我需要从shell输出的第二行获取数据并将其放入另一个shell命令的程序。我想知道如何把第二行的数据放到另一个命令中。你知道吗

第一个shell命令(即init)的输出如下

3467788999987

1007457889308

我只需在第二个命令(即listlogins)中输入“1007457889308”。我在想些什么,我可以在问号上打个问号,以得到第二行数据。有什么吗在format函数中转到某一行并获取该行的数据?你知道吗

init = "symaccess -sid 456 show {0} -type init | grep \"WWN\"".format(WWNname)
print init
logins = os.popen(init).read()
Initiator = logins.replace('       WWN  : ', '')
print Initiator
listlogins = "symaccess -sid 781 list logins -wwn {0}".format(Initiator[??0:17])
Insert = os.popen(listlogins).read()

Tags: 数据命令formatinitosshellprintpopen
1条回答
网友
1楼 · 发布于 2024-10-02 20:32:29

在运行子进程时,最好使用subprocess.Popen()而不是os.popen()。另外,在运行subprocess.Popen()时,最好不要使用选项shell=True。这样做的缺点是不可能使用管道(|)来“堆叠”命令。不过,在当前的示例中,这不是一个大问题,因为grep功能可以在纯Python代码中轻松实现。综上所述,这允许采用类似以下的解决方案:

import subprocess

WWNname = 'something'
init_command = ['symaccess', '-sid', '456', 'show', WWNname, '-type' 'init']
init_output = subprocess.Popen(init_command, stdout=subprocess.PIPE).communicate()[0]
# In Python 2.7 we could do the following instead:
# init_output = subprocess.check_output(command_line)

initiators = []
for line in init_output.split('\n'):
    if 'WWN:' in line: 
        initiators.append(line.replace('WWN:','')

list_command = ['symaccess', '-sid', '781', 'list', 'logins', '-wwn', initators[-1]]
list_output = subprocess.Popen(list_command, stdout=subprocess.PIPE).communicate()[0]

这是不完全一样的,但据我所知,它将产生相同的结果。注意,使用这种方法,可以通过将元素寻址到initiators列表中来选择WWNnumber one需要的元素。具体来说,iniators[-1]将选择列表的最后一个(即第二个)元素。你知道吗

相关问题 更多 >