Reputation: 667
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
Reputation: 14955
No needed for subprocess:
a, d , c = os.walk('.').next()
service_state = d + c
Upvotes: 0
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
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