Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python subprocess return output into a list

Tags:

python

I am trying to create a list with each IP address, returned from the following command. Im not entirely sure how to achieve this. Seems subprocess equals None.

    import subprocess


    ips = list()
    def bash_command(cmd):
        subprocess.Popen(['/bin/bash', '-c', cmd])

    ips = bash_command("netstat -tuna tcp | grep 9876 | grep -v 0.0.0.0 | awk '{ print $5}' | cut -d':' -f1")

    print(ips)
like image 426
Ankh2054 Avatar asked Oct 16 '25 11:10

Ankh2054


2 Answers

In order to read the output you need to direct stdout of your subprocess to a pipe. After that, you can use the readlines function to read the output line by line (or readline to read a single line at a time) , or the read function to read the whole output as a single byte array.

def bash_command(cmd):
    sp = subprocess.Popen(['/bin/bash', '-c', cmd], stdout=subprocess.PIPE)
    return sp.stdout.readlines()
like image 71
Ali Rasim Kocal Avatar answered Oct 18 '25 23:10

Ali Rasim Kocal


As the question title is broad, here is a more generalised version using subprocess.run() which requires different args to return a string. We can call splitlines() on the string to return a list

def subprocess_to_list(cmd: str):
    '''
    Return the output of a process to a list of strings. 
    '''
    return subprocess.run(cmd,text=True,stdout=subprocess.PIPE).stdout.splitlines()

Basic example using ps

# run command
thelist = subprocess_to_list('ps')

# print the output when it completes
print(*thelist[:5],sep = "\n")

Example output from above:

    PID TTY          TIME CMD
   1070 ?        00:00:00 bash
   1071 ?        00:00:00 python3
   1078 ?        00:00:00 sh
   1081 ?        00:00:00 ps
like image 26
lys Avatar answered Oct 19 '25 01:10

lys



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!