#!/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. Android sdcard文件读写操作

    这次演示以,安卓原生操作系统 Nexus_6手机进行操作: AndroidManifest.xml配置相关权限: <!-- 增加权限 --> <uses-permission and ...

  2. WPF 标签预览可以显示图片运行后不显示

    使用<Image HorizontalAlignment="Left" Height="100" Margin="106,111,0,0&quo ...

  3. Oracle数据库多行记录转换一行并排序函数

    Oracle数据库多行记录转换一行并排序方法 在ORACLE数据库查询中,我们通常会要求用到将多行记录转换成一行并排序,这时候我们自然会想到Oracle的一个“wx_concat”函数,可以将多行记录 ...

  4. Elasticsearch、Kibana Windows下环境搭建

    Elasticsearch 簡介 ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口.Elasticsearch是 ...

  5. 无废话网页重构系列——(2)来套Web重构装备

    本篇主要从语言入门.规范.工具.构建.库.框架.版本控制等各方面展开,篇幅会有点长,涉及到的工具类,会另开博文详细介绍. 另外说明Web重构是Web前端的开始,主要侧重Web页面,如实现布局与兼容,符 ...

  6. 基于Spring MVC的web应用随应用启动而加载

    写个类实现org.springframework.context.ApplicationContextAware接口即可. 但是如下的程序会在启动时加载两次: @Controller public c ...

  7. 667. Beautiful Arrangement II

    Given two integers n and k, you need to construct a list which contains n different positive integer ...

  8. java删除字符串最后一个字符的几种方法

    偶然看到的,记录一下,以免忘记 字符串:string s = "1,2,3,4,5," 目标:删除最后一个 "," 方法:    1.用的最多的是Substri ...

  9. What are rules about using an underscore in a c identifier

    http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identi ...

  10. 微信Netting-QRLJacking分析利用-扫我二维码获取你的账号权限

    首先我们来看一下QRLJacking的实际原理:.攻击者首先进行客户端QR会话,并将登录QR码复制到网络钓鱼网站.“现在,一个精心制作的网络钓鱼页面有一个有效和定期更新的QR码可以被发送给受害者.” ...