简体   繁体   中英

How do I execute a complex “find” linux shell command in python

I need to execute the following command:

find PATH -type f -exec du -h --all {} +

Here's my attempt to do this:

import subprocess

result = subprocess.Popen(["find", PATH, "-type", "f", "-exec", "du", "-h", "--all", "{}", "+"], shell=True, stdout=subprocess.PIPE).communicate()[0]
print(result)

And as a result I get some rubbish. What am I doing wrong?

You should only use shell=True when the first argument to Popen() is a string that should be parsed by the shell. If it's an array, you've already done the necessary parsing, and shouldn't use shell=True .

import commands

commands = r'''find PATH -type f -exec du -h --all {} +'''
result = commands.getstatusoutput(command)[0]
print("{}".format(result))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM