How to execute an external command in python and add processing to its output

Asked 2 years ago, Updated 2 years ago, 35 views

I would like to execute a command like catxxx from python and receive the results.
You will receive
execution results.

1aaa3a
2bbb32
3cc50
4ddd41
5eee15

It assumes a string similar to .
I'd like to separate each line of this string into fields with a space, add processing to each field, and print it out.

  • Outputs the first and second fields as they are
  • Think of the third field (e.g., 30) as a hexadecimal expression string and convert it into a numerical value, and perform the following bit operation.
    • Output the 5th bit (0 or 1) into the 3rd field
    • Output the 4th bit (0 or 1) into the 4th field
    • 3rd to 1st bits in decimal representation (0~)7)Output to 5th Field in
  • Output the 5th bit (0 or 1) into the 3rd field
  • Output the 4th bit (0 or 1) into the 4th field
  • 3rd to 1st bits in decimal representation (0~)7)Output to 5th Field in

Sample Output:

1aaa1 1 2
2bbb102
3cc 100
4ddd001
5eee 10 5

Is it possible to process it like this?

python

2022-09-30 20:12

3 Answers

I don't know where the prerequisites are, but I recommend that you think as follows:

  • Run catxxx from Python -->Open and load file xxx in Python


2022-09-30 20:12

Is this what it looks like? This code is print. I might keep it as a string and use it for later tasks.

import subprocess

contents=subprocess.check_output('catxxx', shell=True)
for lin contents.splitlines():
    e=l.split()
    number=int(e[2], base=16)
    print(e[0], e[1], number>>4&1, number>3&1, number&0b111)


2022-09-30 20:12

@Takayuki As SHIMIZUKAWA said, if the cat feature is available, it should be loaded in Python file.

However, if all output does not appear immediately, such as cat, especially tail-F, you should use iter.

from subprocess import Popen,PIPE

p = Popen (['cat', xxx], stdout = PIPE)

for line inter(p.stdout.readline, ''):
    Please refer to @takoika's answer for how to implement process_content(line)#process_content


2022-09-30 20:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.