解析命令调用

时间:2016-08-23 02:37:38

标签: 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应该是一个长字符串,我试图解析字符串并将显着字符存储到另一个要使用的数组中,但我想分析数据。

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命令。

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

1 个答案:

答案 0 :(得分:1)

引用Aaron Maenpaaanswer

  

您需要解码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

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

修改

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

  

communic()方法返回一个字节数组:

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