Swaroop Kundeti
Swaroop Kundeti

Reputation: 667

Output of command to list using Python

I'm writing an automation script, where it needs to run a command and the output of command should be captured as a list.

For example:

# ls -l | awk '{print $9}'
test1
test2

I want the output to be captured as a list like var = ["test1", "test2"].

Right now I tried this but it is saving as string instead of list:

# Filter the tungsten services
s = subprocess.Popen(["ls -l | awk '{print $9}'"], shell=True, stdout=subprocess.PIPE).stdout
service_state = s.read()

Please guide me if anyone has any idea to achieve this.

Upvotes: 2

Views: 14419

Answers (3)

Juan Diego Godoy Robles
Juan Diego Godoy Robles

Reputation: 14955

No needed for subprocess:

a, d , c = os.walk('.').next()
service_state = d + c

Upvotes: 0

Aaron Digulla
Aaron Digulla

Reputation: 328594

You can use

service_states = s.read().splitlines()

but note that this is brittle: File names can contain odd characters (like spaces).

So you're probably better off using os.listdir(path) which gives you a list of file names.

Upvotes: 5

OBu
OBu

Reputation: 5177

You can post-process the string according to your needs.

string.splitlines() (https://docs.python.org/2/library/stdtypes.html#str.splitlines) will break the string into a list of lines.

If you need to split the results further, you can use .split().

Upvotes: 0

Related Questions