3

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.

3
  • 1
    just use s.read().splitlines() Commented Jul 18, 2014 at 11:25
  • use shlex.split() on your command string; unless you want some bugs in your software. Commented Jul 18, 2014 at 11:30
  • I wouldn't parse ls -l if you don't need to mywiki.wooledge.org/ParsingLs. You can use globbing with * to expand all files and directories in the current directory. e.g. echo * Commented Jul 18, 2014 at 12:18

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@SwaroopKundeti: Then you might want to accept the answer: stackoverflow.com/help/accepted-answer
Thanks Aaron, I dint know how to accept the answer, Thanks so much
If your command returns multiple lines but you are getting the output in a single line from subprocess.check_output , then use splitlines() directly on subprocess.check_output like result_list = subprocess.check_output(...).splitlines()
0

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

Comments

0

No needed for subprocess:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.