Python 解析来自命令调用的输出

Python 解析来自命令调用的输出,python,string,subprocess,stdout,popen,Python,String,Subprocess,Stdout,Popen,因此,我尝试从python执行一个shell命令,然后将其存储在数组中,或者直接解析管道shell命令 我通过subprocess命令管道化shell数据,并使用print语句验证输出,结果很好 a = subprocess.Popen('filepath/command', shell=True, stdout=subprocess.PIPE) b = a.stdout.read() print(b) 现在,我试图从未知数量的行和6列中解析出数据。因为b应该是一个长字符串,所以我尝试解析该字

因此,我尝试从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_输出

from subprocess import check_output
a = check_output('file/path/command')
这给了我一个权限错误,所以如果可能的话,我想使用Popen命令

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

引用:

您需要解码bytes对象以生成字符串:

>>> 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
顺便说一句,我不太理解您的解析代码,这会给您一个
类型错误:列表索引必须是整数,而不是tuple
,因为您要在
中向列表索引传递一个tuple(假设它是一个列表)

编辑 请注意,调用
print
内置方法不是检查传递的参数是否为纯字符串类型对象的方法。从引用答案的OP中:

communicate()方法返回字节数组:

>>> 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'
但是,我希望将输出作为普通Python字符串使用。 这样我就可以这样打印:

>>> 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

因为我用print命令验证了它是一个字符串,所以这不是验证它是一个字符串的方法。。。显然,它不是字符串类型的对象,否则不会出现错误。不能在
str
上拆分
字节,请使用
b.split(b'\n\n')
line.split(b'')
检查此问题:如果您向我提供了预期输出,我可以帮助您解决问题的第二部分。预期输出与您引用的command_stdout答案一样-rw-rw-r--1托马斯·托马斯3月0日07:03文件1。假设这行可以是未知数量的行和6列。每一行用一个空行隔开