[英]how to store return value and NOT command call status using python script?
I am trying to test if a path exist in hadoop using python script. 我正在尝试使用python脚本测试hadoop中是否存在路径。
hdfs dfs -test -e /path/to/file
The above will return 0 if path exists, 1 if path doesn't exist. 如果路径存在,则以上将返回0,如果路径不存在,则将返回1。 Below is my python script:
以下是我的python脚本:
if subprocess.call("hdfs dfs -test -e /path/to/file", shell = True) == 0:
# do something
The above code it's not working, subprocess is always 0 b/c it's checking the command status not the returned value. 上面的代码不起作用,子进程始终为0 b / c,它正在检查命令状态而不是返回值。 I found this post , but didn't seem to work.
我找到了这篇文章 ,但似乎没有用。 I also tried storing the return value of echo
result = subprocess.call("echo $?", shell = True)
, also didn't work. 我还尝试存储echo
result = subprocess.call("echo $?", shell = True)
的返回值,也没有用。
Below is my full code: 下面是我的完整代码:
#!/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")
Change run_commands
to 将
run_commands
更改为
def run_commands(func, path):
return subprocess.call(HDFS + func + path, shell = True)
run_commands
is not automatically returning the return code from subprocess.call
. run_commands
不会自动返回从返回代码subprocess.call
。 It will return None
. 它将返回
None
。 (Tested in python 2.6.6). (在python 2.6.6中测试)。
Because of that, if run_commands("-test -e ", path) == 0
will not be true. 因此,
if run_commands("-test -e ", path) == 0
将不成立。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.