簡體   English   中英

剪切os.system輸出的一行並將其寫入文件

[英]Cutting one line of the output of os.system and write that to a file

當我在終端中執行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

並繼續。

我想使用os.system("...")在python腳本中執行該命令,然后提取始終以4:開頭的行並將其打印到txt文件中。 我怎樣才能做到這一點? 我可以告訴python剪切輸出的第11行嗎? 還是在行首搜索4:

大多數Linux系統沒有使用Python處理此問題,而是提供了一些有用的文本字符串處理工具。 實際上,大多數這些工具通常用於在內容流中搜索有用的模式。

4:打印行4:

我們可以為此使用grep [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行(包括4:行) 4:

您可以為此使用sed [wiki] 通過寫sed '/pattern/q'您將打印內容,直到(包括) pattern匹配的行。

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

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

我們可以使用子進程的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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM