python - 从我保存在本地文件系统上的配置单元查询输出中删除空行

标签 python hadoop hive

我正在我的devbox上运行一个python脚本,以在网格网关盒上远程ssh来启动另一个运行hive查询并返回输出的python脚本,然后将它以datestamp.tsv格式保存在我的devbox上。

对于某些查询,我必须为两个群集运行一个for循环。问题是输出正在保存,但是有空行,我希望日期戳在查询输出之后。这是我现在的输出-

2014_03_28 PT 588.12    396.73

2014_03_28 DB 0.17      0.0

每次在for循环中运行查询后,都会有一个空行。

如何删除空行?并将日期戳放在最后。我希望它的输出格式是
PT 588.12    396.73 2014_03_28
DB 0.17      0.0  2014_03_28

父脚本:
def get_compute_resources():
  global output
  ensure_directory(pipeline_name, user, star_date, "daily_compute_resources")
  for grid in grids:
    cmd = 'ssh -2 -i /home/abcd/.ssh/id_dsa -l abcd -o StrictHostKeyChecking=no -o CheckHostIP=no hostname "python2.6 /homes/abcd/starling/fetch_daily_user_summary.py -u ' + user + ' -g ' + grid + ' -d ' + starling_date + '" >> /home/abcd/projects/starling/daily_compute_resources/'+ pipeline_name +'/'+ user +'/'+ starling_date +'.tsv'
    resources = make_call(cmd).rstrip()
    print resources

远程机器脚本:
cmd = "/home/y/bin/hive -e 'use star; SELECT ROUND(SUM((map_slot_seconds)/3600/24/2),2), ROUND(SUM((reduce_slots_seconds)/3600/24/2),2) from starling_job_summary where user=%s and grid=%s and dt like %s group by dt;' -hiveconf mapred.job.queue.name=unfunded -hiveconf mapred.reduce.tasks=1" % (user, grid, date)
  resources = Popen(cmd, shell=True, stdout=PIPE).communicate()[0]
  output = output_date+' '+output_grid+' '+resources
  print output

谢谢。

最佳答案

这应该工作。假设您在执行python的同一目录中拥有名为input.txt的文件提供的数据,并以output.txt文件所需的格式提供了数据。 if line.strip()检查将仅忽略完全为空格的行,除此之外,唯一有点酷的地方是split()的maxsplit参数,该参数将日期与行的其余部分分隔开。

infile = 'input.txt'
outfile = 'output.txt'

with open(infile) as f:
    with open(outfile, mode='w') as output:
        data = f.readlines()
        for line in data:
            if line.strip():
                date, rest = line.split(maxsplit=1)
                date = date.strip()
                rest = rest.strip()
                output.write(rest + ' ' + date + "\n")

也许可以对空白处理进行一些清理,但这更加简单。

输出:
PT 588.12    396.73 2014_03_28
DB 0.17      0.0 2014_03_28

关于python - 从我保存在本地文件系统上的配置单元查询输出中删除空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23920423/

相关文章:

Python 命令 print() 不打印

java - 从 Android : Java or Python (SL4A) 开始

Python装饰器跳过被装饰函数的代码

python - Python 中的类继承问题

hadoop - 谁能说可以使用Java创建配置单元外部表

csv - 如何将具有不同分隔符的 CSV 加载到单个 Hadoop 表

azure - 当前正在安装Windows Azure Pack:网站v2,但在我的Web安装程序4.6中不存在该文件,这是什么原因?

spring - Spring Data Hadoop中如何根据 `timestamp`过滤记录?

hadoop:如何显示put命令的执行时间?或者如何显示在 hdfs 中加载文件的持续时间?

hadoop - 无法保留HIVE表