解析命令调用的输出

parsing output from command call

所以我试图从 python 执行 shell 命令,然后将其存储在数组中或直接解析管道 shell 命令。

我正在通过 subprocess 命令传输 shell 数据,并使用 print 语句验证输出,它工作得很好。

a = subprocess.Popen('filepath/command', shell=True, stdout=subprocess.PIPE)
b = a.stdout.read()
print(b)

现在,我正在尝试从未知数量的行和 6 列中解析出数据。由于 b 应该是一个长字符串,我尝试解析该字符串并将显着字符存储到另一个数组中以供使用,但是我想分析数据。

i = 0
a = subprocess.Popen('filepath/command', shell=True, stdout=subprocess.PIPE)
b = a.stdout.read()
for line in b.split("\n\n"): #to scan each row with a blank line separating each row
    salient_Chars[i, 0] = line.split(" ")[3] #stores the third set of characters and stops at the next blank space
    salient_Chars2[i, 0] = line.split(" ")[4] #stores the fourth set of characters and stops at the next blank space
    i = i + 1

我收到错误 [TypeError: 需要类似字节的对象,而不是 'str']。我搜索了这个错误,这意味着我使用 Popen 存储了字节而不是字符串,我不确定为什么,因为我用 print 命令验证了它是一个字符串。在搜索如何将 shell 命令通过管道传输到字符串后,我尝试使用 check_output。

from subprocess import check_output
a = check_output('file/path/command')

这给了我一个权限错误,所以我想尽可能使用 Popen 命令。

如何将管道 shell 命令转换为字符串,然后如何正确解析分为行和列的字符串,列与列之间有空格,行与行之间有空行?

引用 Aaron Maenpaa's answer:

You need to decode the bytes object to produce a string:

>>> b"abcde"
b'abcde'

# utf-8 is used here because it is a very common encoding, but you
# need to use the encoding your data is actually in.
>>> b"abcde".decode("utf-8") 
'abcde'

因此您的代码如下所示:

i = 0
a = subprocess.Popen('filepath/command', shell=True, stdout=subprocess.PIPE)
b = a.stdout.read().decode("utf-8") # note the decode method
for line in b.split("\n\n"): #to scan each row with a blank line separating each row
    salient_Chars[i, 0] = line.split(" ")[3] #stores the third set of characters and stops at the next blank space
    salient_Chars2[i, 0] = line.split(" ")[4] #stores the fourth set of characters and stops at the next blank space
    i = i + 1

顺便说一句,我不太理解你的解析代码,它会给你一个 TypeError: list indices must be integers, not tuple 因为你将一个元组传递给 salient_Chars 中的列表索引(假设它是一个列表)。

编辑

请注意,调用 print 内置方法 不是 一种检查传递的参数是否为普通字符串类型对象的方法。来自引用答案的 OP:

The communicate() method returns an array of bytes:

>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2\n'

However, I'd like to work with the output as a normal Python string. So that I could print it like this:

>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2