切割输出的一行操作系统然后写给一个fi

2024-05-12 21:26:56 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在终端中执行objdump命令时,我得到如下结果

$ objdump -d -M intel -S -z machine3.o

machine3.o:     file format elf64-x86-64


Disassembly of section .text:

0000000000000000 <main>:
void main() {
   0:   55                      push   rbp
   1:   48 89 e5                mov    rbp,rsp
   4:   00 00                   add    BYTE PTR [rax],al
   6:   00 00                   add    BYTE PTR [rax],al

这种情况还在继续。你知道吗

我想在python脚本中使用os.system("...")执行该命令,然后将总是以4:开头的行提取并打印到txt文件中。我该怎么做?我能告诉python剪切输出的第11行吗?或者在行首搜索起始4:?你知道吗


Tags: 命令addformat终端mainbytefilerax
2条回答

我们可以使用subprocess的Popen方法来提取输出,并验证行是否包含“4:”,然后将该行写入文本文件,这可以实现以下目的:)。你知道吗

示例

import subprocess

def main():

    """ Popen containining our objdump command """
    process = subprocess.Popen(['objdump', '-d', '-M', 'intel', '-S', '-z', 'machine3.o'], stdout=subprocess.PIPE)

    """ Retrieve output or errors """
    out, err = process.communicate()

    """ Loop through our output """
    for line in out.splitlines():

        """ Check line contains our line-break 4: """
        if '4:' in line:

            """ Write line to our file """
            with open('somefile.txt', 'a') as the_file:
                the_file.write(line)

            """ End our for loop """
            break

if __name__ == '__main__':
    main()

大多数Linux系统没有用Python处理这个问题,而是为文本字符串提供了一些有用的处理工具。事实上,这些工具中的大多数通常用于在内容流中搜索有用的模式。你知道吗

4:打印行

我们可以使用^{} [wiki]来实现:

objdump -d -M intel -S -z test.o | grep '^\s*4:'

如果我们只对第一个匹配感兴趣,我们可以使用-m标志,如:

objdump -d -M intel -S -z test.o | grep '^\s*4:' -m 1

打印行到(包括)4:

你可以用^{} [wiki]来做这个。通过编写sed '/pattern/q',您将打印内容直到(包括)匹配pattern的行。你知道吗

因此,您可以运行以下命令:

objdump -d -M intel -S -z machine3.o | sed '/\s*4:/q'

相关问题 更多 >