我在服务器上使用python v3.4,我经常需要将多个文件从本地目录复制/移动到hdfs目录。我的所有文件都在子目录中,而子目录又在 MyDir 中。这是我使用的命令-
$ hdfs dfs -copyFromLocal MyDir/* /path/to/hdfs/
此命令在服务器上运行良好,但是当我使用子进程在python中使用相同的命令时
>>> subprocess.call(['hdfs', 'dfs', '-copyFromLocal', 'MyDir/*', '/path/to/hdfs/'])
它给出了以下错误-
copyFromLocal: `MyDir/*': No such file or directory
1
附言-我也尝试了['hadoop', 'fs', '-put'....]
而不是['hdfs', 'dfs', '-copyFromLocal'....]
,它也不起作用。
谁能帮我解决这个问题?任何帮助将不胜感激。
编辑 - 我需要将文件与子目录一起移动。
添加shell=True
:
>>> subprocess.call(['hdfs', 'dfs', '-copyFromLocal', 'MyDir/*', '/path/to/hdfs/'], shell=True)
阅读这篇文章: 子流程中"shell=True"的实际含义
我会编写一个带有子进程的函数,它为您提供输出和错误:
import subprocess
def run_cmd(args_list):
"""
run linux commands
"""
# import subprocess
print('Running system command: {0}'.format(' '.join(args_list)))
proc = subprocess.Popen(args_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
s_output, s_err = proc.communicate()
s_return = proc.returncode
return s_return, s_output, s_err
然后:
import os
for file in os.listdir('your-directory'):
run_cmd(['hadoop', 'fs', '-put', 'your-directory/{0}'.format(file), 'target-directory'])
这应该遍历目录中的所有文件,并将它们放在所需的HDFS目录中
将命令中的所有内容追加到单个字符串中,并给出参数shell = True
subprocess.call('hdfs dfs -copyFromLocal MyDir/* /path/to/hdfs/', shell = True)