如何使用python脚本存储返回值和NOT命令调用状态?

时间:2015-08-13 16:37:41

标签: python shell hadoop

我正在尝试使用python脚本测试hadoop中是否存在路径。

hdfs dfs -test -e /path/to/file

如果路径存在,上面将返回0,如果路径不存在,则返回1。下面是我的python脚本:

if subprocess.call("hdfs dfs -test -e /path/to/file", shell = True) == 0:
    # do something

上面的代码没有用,子进程总是0 b / c它检查命令状态而不是返回值。我找到了post,但似乎没有用。我也试过存储echo result = subprocess.call("echo $?", shell = True)的返回值,也没用。

以下是我的完整代码:

#!/usr/bin/env python
import subprocess

HDFS = "hdfs dfs "

def run_commands(func, path):
    subprocess.call(HDFS + func + path, shell = True)

def path_exist(path):
    return True if run_commands("-test -e ", path) == 0 else False

path_exist("/path/to/file")

1 个答案:

答案 0 :(得分:1)

run_commands更改为

def run_commands(func, path):
    return subprocess.call(HDFS + func + path, shell = True)

run_commands不会自动从subprocess.call返回返回代码。它将返回None。 (在Python 2.6.6中测试过)。

因此,if run_commands("-test -e ", path) == 0将不属实。

相关问题