Ankh2054
Ankh2054

Reputation: 1153

Python subprocess return output into a list

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)

Upvotes: 4

Views: 8251

Answers (2)

lys
lys

Reputation: 1027

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

Upvotes: 1

Ali Rasim Kocal
Ali Rasim Kocal

Reputation: 540

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()

Upvotes: 6

Related Questions