2

I want to simulate the following unix commands:

f=`find . -name "*.pdf"`
for file in $f; do echo "$f"; done

I have the following python command:

out= subprocess.check_output(["/usr/bin/find", ".", "-name",  "*.pdf"]).strip()

But I can't access out[0] or out[1] and so on. Is it possible to return the output in python as an array of strings, so I can iterate over each of them and do something with it? Thanks

2
  • 1
    Why, when os.walk() is a thing? Commented Dec 13, 2014 at 15:23
  • This is just an example I came up with to illustrate what I want. To rephrase this in another way - I want to execute a command which returns output, and I want to iterate over each line in that output generated. So os.walk() wouldn't help in that use case. Commented Dec 13, 2014 at 15:25

1 Answer 1

3

str.strip() remove spaces around the string. You need to str.splitlines to split lines:

>>> 'a\nb'.strip()
'a\nb'
>>> 'a\nb\n'.splitlines()
['a', 'b']

out = subprocess.check_output(["/usr/bin/find", ".", "-name",  "*.pdf"]).splitlines()
Sign up to request clarification or add additional context in comments.

6 Comments

Awesome! exactly what I was looking for.
No, the use of strip is incorrect, and the use of splitlines() is wrong if find ever outputs a file name which contains a newline. The safe, reliable way is to use find -print0 and split on nulls. This is a FAQ.
@tripleee How do u split on nulls?
@Bill, line.split('\0') ('\0' means null character)
@tripleee, Thank you for pointing filenames with newline. BTW, if OP really want to list files, OP could use os.walk instead of subprocess.*. str.strip was used to demonstrate that the method is not what OP want.
|

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.