#!/usr/bin/env python
# -- coding:utf-8 --

import os
import sys
from subprocess import call

from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession

#master = spark://spark:7077

master = os.environ.get("SPARK_MASTER_URL")
spark = SparkSession.builder \
    .master(master) \
    .appName("hive") \
    .enableHiveSupport() \
    .getOrCreate()

TIMESTAMP_COLUMNS = ['created', 'date', 'create', 'time', 'launchDate']

def refresh_model(model):
    df = spark.sql('select * from {model}'.format(model=model))
    df.show()
    first = df.first() or []
    time_columns = filter(lambda key: key in first, TIMESTAMP_COLUMNS)

partition_column = None

if time_columns:
        partition_column = time_columns[0]

if 'id' in first:
        partition_column = 'id'

if not time_columns:
        return

spark.sql('drop table if exists {model}'.format(model=model))
    df.repartition(time_columns[0]).write.saveAsTable(model)

def run(filePath):
    filePath = os.path.join(os.getcwd(), filePath)
    executor = None
    if 'postsql' in filePath:
        executor = '/data/spark-2.2.0-bin-hadoop2.7/bin/spark-sql'
    else:
        executor = '/data/apache-hive-2.1.1-bin/bin/hive'

call("{} -f {}".format(filePath, executor),shell=True)

model = os.path.splitext(os.path.basename(filePath))[0]
    if executor == 'hive':
        print('model', model)
        refresh_model(model)

if __name__ == '__main__':
    if len(sys.argv) == 2:
        run(sys.argv[1])
    else:
        valid_dirs = ['sql', 'postsql']
        for dir in valid_dirs:
            for dirpath,dirnames,filenames in os.walk(dir):
                for filename in filenames:
                    run(os.path.join(dirpath,filename))

主要理解os.path.join()、os.walk()、os.getcwd()几个方法的用法,进行路径拼接。

注意一个地方的写法:

call("{} -f {}".format(filePath, executor),shell=True)

当然也可以写成subprocess.call("{} -f {}".format(filePath, executor),shell=True)

shell=True是后加上的,如果没有shell=True,call("{} -f {}".format(filePath, executor))使用pipeline创建任务执行是会报错。

pipeline {
    agent {label 'spark' }
    stages {
        stage('hive sql'){
            steps{
                dir('/data/sftp/huoqiu/script'){
                    sh 'python hive.py'
                }
            }
        }
    }
}
执行后就会报下面的错:
Traceback (most recent call last):
File "./marp.py", line 82, in <module>
programs = [ subprocess.Popen(c) for c in commands ]
File "/usr/lib/python2.6/subprocess.py", line 595, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1092, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
解决放方法就是:
call("{} -f {}".format(filePath, executor),shell=True)
在最后加上shell=True,就不会报错,能够正确执行。

python hive.py的更多相关文章

  1. python调用py中rar的路径问题。

    1.python调用py,在py中的os.getcwd()获取的不是py的路径,可以通过os.path.split(os.path.realpath(__file__))[0]来获取py的路径. 2. ...

  2. python gettitle.py

    #!/usr/bin/env python # coding=utf-8 import threading import requests import Queue import sys import ...

  3. Python pydoc.py

    1. 查看帮助,我们可以在python命令行交互环境下用 help函数,比如: 查看 math 模块: >>> help('math')Help on built-in module ...

  4. django 1.7之后python manage.py syncdb没有了

    在命令行输入python manage.py createsuperuser按照提示输入即可记得先初始化表. django>1.7 python manage.py makemigrations ...

  5. Python安装mysql-python错误提示python setup.py egg_info

    做python项目,需要用到mysql,一般用python-mysql,安装时遇到错误提示如下: Command "python setup.py egg_info" failed ...

  6. python __init__.py用途

    转自http://www.cnpythoner.com/post/2.html Python中的Module是比较重要的概念.常见的情况是,事先写好一个.py文 件,在另一个文件中需要import时, ...

  7. python setup.py uninstall

    I have installed a python package with python setup.py install How do I uninstall it? ============== ...

  8. python 运行python manege.py runserver时报错:“no module named djangorestframework” 的解决方案

    python 运行python manege.py runserver时报错:“no module named djangorestframework” 的解决方案 importerror:no mo ...

  9. Python Web.py

    安装Web.py root@bt:~# sudo pip install web.py Downloading/unpacking web.py Downloading web.py-0.37.tar ...

随机推荐

  1. 个人项目:实现wc.exe(Java)

    本项目Github地址:https://github.com/NNewBoy/wc 项目相关要求 基本功能:(已实现) -c 统计文件字符数 -w 统计文件词的数目 -l 统计文件行数 扩展功能:(已 ...

  2. 删除map、list集合元素总结

    @Testpublic void removeElementFromMap(){Map<Integer, String> test = new HashMap<Integer, St ...

  3. Google Summer of Code礼包

    这个暑假参加google summer of code, 给Google的分布式容器管理系统kubernates开发新的特性,希望从中学习更多的分布式的技术,锻炼自己的编程技巧. 中午在学校的图书馆吗 ...

  4. 盘古分词+一元/二元分词Lucene

    本文参考自:https://blog.csdn.net/mss359681091/article/details/52078147 http://www.cnblogs.com/top5/archiv ...

  5. ASP.NET Core SignalR CORS 跨域问题

    将 SignalR 集成到 ASP.NET Core api 程序的时候,按照官方 DEMO 配置完成,本地访问没有问题,但是发布之后一直报跨域问题,本地是这样设置的: 原始代码: services. ...

  6. 使用Spring Boot,Spring Cloud和Docker实现微服务架构

    https://github.com/sqshq/PiggyMetrics     Microservice Architecture with Spring Boot, Spring Cloud a ...

  7. Hessian——轻量级远程调用方案

    Hessian是caucho公司开发的一种基于二进制RPC协议(Remote Procedure Call protocol)的轻量级远程调用框架.具有多种语言的实现,但用的最多的当然是Java实现 ...

  8. s11 day100路飞项目逻辑购物车一

    Luffy项目 先看练习,如下: 一. 添加购物车和查看 1. url url(r'^shoppingcar/$', shoppingcar.ShoppingCarView.as_view({&quo ...

  9. 689. Maximum Sum of 3 Non-Overlapping Subarrays

    In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum. E ...

  10. 配置国内的maven仓库

    MAVEN中央仓库 国内 配置Maven中央仓库路径的方法如下: 在Maven文件的conf目录中打开settings.xml文件 在文件中的servers节点和mirror节点中加入如下内容 华为云 ...