【问题标题】:parsing output from command call解析命令调用的输出
【发布时间】:2016-08-23 02:37:38
【问题描述】:

所以我试图从 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 命令转换为字符串,然后如何正确解析一个字符串,该字符串分为行和列,列之间有空格,行之间有空行?

【问题讨论】:

  • 因为我用 print 命令验证了它是一个字符串 嗯,这不是验证它的一个字符串的方法......显然它不是 字符串类型的对象,否则不会引发该错误。
  • 你不能在str上拆分bytes,使用b.split(b'\n\n')line.split(b' ')
  • 如果您向我提供预期的输出,我可以帮助您解决问题的第二部分
  • 预期输出就像您引用的 command_stdout 答案一样。 -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1。想象一下,这条线可以是未知数量的行和 6 列。每行由一个空行分隔

标签: python string subprocess stdout popen


【解决方案1】:

引用Aaron Maenpaaanswer

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-25
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多