Implementation of the Linux find command in python

2019-09-12 05:54发布

问题:

Can someone point me to a set of instructions of how to actually implement and utilize the find command within a Python script?

I have looked at: https://docs.python.org/2/library/subprocess.html I'm not exactly sure how to utilize the command, even if implementation goes well with either subprocess.call or subprocess.Popen. From all of the SO threads that I've read concerning this topic, it seems like these are the two best options. However, I am not sure what kind of arguments I would need to use, as well as how to specifically implement the find command within them.

Can someone please demonstrate how to use find in the context of subprocess.call or subprocess.Popen so that I can later call find directly in my Python script?

回答1:

You probably want to use the check_output() helper function.

find_output = subprocess.check_output('find ~', shell = True)

In the above example, find_output will contain a bytes instance of the find commands stdout. If you wish to capture the stderr as well, add stderr=subprocess.STDOUT as a keyword argument.



回答2:

How about this,

found = subprocess.Popen(['find', '.'],stdout=subprocess.PIPE)
for line in iter(found.stdout.readline, ''):
   print line,