python 子进程检查输出:如何获取整个消息

python subprocess check output: how to get the entire message

我正在使用 subprocess.check_output 删除 hadoop 中的文件夹,并希望能够获得与从控制台执行 hadoop 命令相同的结果。

因此,我可能会尝试删除多个目录,其中一些目录不存在。

此命令完全失败(因为找不到我的 'nonexisting' 目录)

subprocess.check_output('hadoop fs -rm -r -skipTrash my_host/path_to_existing_directory my_host/path_to_nonexisting_directory', shell = True)

为了防止失败我可以这样做:

try:
    subprocess.check_output('hadoop fs -rm -r -skipTrash  my_host/path_to_existing_directory/ my_host/path_to_nonexisting_directory', shell = True)
except subprocess.CalledProcessError as e:
    print(e.output, 'some of the folders were not found')

第二个选项更好,因为它告诉我删除了哪些目录(如果有的话)。为了区分有些不是,我可以将 'some of the folders were not found' 添加到我的打印输出中。

但是,当我从命令行执行相同的命令时,我得到了更好的信息,我想复制这些信息:

hadoop fs -rm -r -skipTrash  my_host/path_to_existing_directory/ my_host/path_to_nonexisting_directory

Returns:

Deleted my_host/path_to_existing_directory
rm: `my_host/path_to_nonexisting_directory': no such file or directory

该进程可能会将错误消息写入标准错误stderr,您也可以通过重定向捕获它使用参数 stderr=subprocess.STDOUT

到标准输出 stdout

因此,您的代码将如下所示:

try:
    output = subprocess.check_output('...', shell = True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    print(e.output, 'some of the folders were not found')