【发布时间】:2013-11-03 01:22:45
【问题描述】:
我对 python 和 subprocess 模块比较陌生。
我正在尝试使用 mac osx 上的子进程通过 python 获取目录大小。 os.walk 需要很长时间来处理大型目录。我希望让子进程使用 shell 命令执行此操作并加快结果。这个 shell 命令对我有用,但我不能让它从子进程中工作?
( cd /test_folder_path && ls -nR | grep -v '^d' | awk '{total += $5} END {print total}' )
这就是我尝试在 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) init 中的文件“/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py”,第 711 行 读错,写错) _execute_child 中的文件“/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py”,第 1308 行 引发 child_exception OSError: [Errno 2] 没有这样的文件或目录
当我在 shell 命令中使用相同的目录时,它可以工作并为我提供正确的目录大小。
任何帮助使这种方法发挥作用或向我指出更好的方法将不胜感激。
【问题讨论】:
-
怎么了?蟒蛇错误? Cmd 行语法错误?答案错误?
-
试试
cd /test_folder_path && du -c | tail -n 1
标签: python macos shell directory subprocess