首页 文章

使用python子进程在mac上获取目录大小而不是os.walk

提问于
浏览
0

我是python和子进程模块的新手 .

我正在尝试使用mac osx上的子进程使用python获取目录大小 . os.walk需要很长时间才能找到大型目录 . 我希望通过shell命令让子进程执行此操作并加快结果 . 这个shell命令对我有用,但我不能让它从子进程工作?

(cd / test_folder_path && ls -nR | grep -v'^ d'| awk'{total = $ 5} END ')

这就是我试图在python中创建子进程的方法 .

import shlex 
import subprocess

target_folder = "/test_folder_path"
command_line = "( cd " + target_folder + " && ls -nR | grep -v '^d' | awk '{total += $5} END {print total}' )"
args = shlex.split(command_line)
print args
folder_size = subprocess.check_output(args)
print str(folder_size)

在python中,我调用subprocess.check_ouput时会出现以下错误

folder_size = subprocess.check_output(args)文件"/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py",第568行,在check_output进程中= Popen(stdout = PIPE,* popenargs,** kwargs)文件"/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py",第711行,在 init errread,errwrite)文件"/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py",第1308行, _execute_child raise child_exception OSError:[Errno 2]没有这样的文件或目录

当我在shell命令中使用相同的目录时它工作,并给我正确的大小目录 .

任何帮助使这种方法工作或指向我更好的方法将非常感激 .

1 回答

  • 2

    python的子进程默认使用 shell=False . 为了使用管道运行子命令,您需要shell来防止python将管道(和 && )解释为 cd 的参数 .

    target_folder = "/test_folder_path"
    command_line = "cd " + target_folder + " && ls -nR | grep -v '^d' | awk '{total += $5} END {print total}'"
    folder_size = subprocess.check_output(command_line, shell=True)
    

    我已经尝试了上述内容,只使用了drewk建议的命令:

    >>> import subprocess
    >>> folder_size = subprocess.check_output('cd ~/mydir && du -c | tail -n 1', shell=True)
    >>> folder_size
    b'113576\ttotal\n'
    

    一切似乎都很好 .

    如注释中所述, subprocess.Popen (以及扩展名为 check_output )也接受 cwd 参数,该参数是运行命令的目录 . 这消除了在命令中更改目录的需要:

    >>> import subprocess
    >>> result = subprocess.check_output('du -c | tail -n 1', cwd='/path/to/home/mydir', shell=True)
    >>> result
    '113576\ttotal\n'
    

相关问题