繁体   English   中英

在python数组中捕获bash输出

[英]Capture bash output in a python array

我有一个bash脚本,需要将其转换为python程序。

我运行命令并在bash数组中捕获其输出,并对其进行迭代。

diskArr=(`lsblk | grep 'disk' | awk -v col1=1 '{print $col1}'`)

该命令为我提供了系统中所有硬盘的列表,并将其存储在阵列“ diskArr”中。

我尝试使用os.system和subprocess.Popen,但没有成功。

>>> import shlex, subprocess
>>> command_line = raw_input()
lsblk | grep 'disk' | awk -v col1=1 '{print $col1}'
>>> args = shlex.split(command_line)
>>> print args
['lsblk', '|', 'grep', 'disk', '|', 'awk', '-v', 'col1=1', '{print $col1}']
>>>
>>>
>>> subprocess.Popen(args)
<subprocess.Popen object at 0x7f8e083ce590>
>>> lsblk: invalid option -- 'v'

Usage:
 lsblk [options] [<device> ...]

到目前为止,您实际上并没有将程序转换为python,而只是在尝试使用python作为shell的包装器。 但是您也可以在python中进行grepping和aking:

import subprocess
import re

lsblk = subprocess.Popen(['lsblk'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in lsblk.stdout:
    if 'disk' in line:
        parts = re.split(r'\s+', line.strip())
        name, majmin, rm, size, ro, devtype = parts[:6]
        if len(parts) > 6:
            mountpoint = parts[6]
        else:
            mountpoint = None
        print(majmin)
returncode = lsblk.wait()
if returncode:
    print("things got bad. real bad.")

那只是一个例子。 如果您想要一个引用磁盘的行列表,则可以构建一个列表,其中包含其中包含“磁盘”的行:

lsblk = subprocess.Popen(['lsblk'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
blockdevs = [line.strip() for line in lsblk.stdout if 'disk' in line]
returncode = lsblk.wait()
if returncode:
    print("things got bad. real bad.")
print(blockdevs)

您可以在官方文档中查看如何替换Shell管道 ,它提供了一个很好的示例,说明您正在尝试执行的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM