spark context stop use with as
调用方法:
- with session.SparkStreamingSession('CC_Traffic_Realtime', ssc_time_windown) as ss_session:
- kafkaStreams = ss_session.get_direct_stream(TOPICNAME)
- kafkaStreams.transform(xxxx)...
- ss_session.ready_to_go()
实现方法:
- import pickle
- from io import BytesIO
- from pyspark import SparkConf
- from pyspark import SparkContext
- from pyspark.streaming import StreamingContext
- from pyspark.streaming.kafka import KafkaUtils
- class SparkgSession(object):
- __APP_PATH = "hdfs://hacluster/tmp"
- def __init__(self, app_name):
- self._sc = SparkContext(appName=app_name)
- def __enter__(self):
- return self
- def __exit__(self, e_type, e_value, e_traceback):
- self._sc.stop()
- def _get_full_path(self, file_path):
- return "{}/{}".format(self.__APP_PATH, file_path)
- def load_model(self, pkl_file_path):
- full_path = self._get_full_path(pkl_file_path)
- rdd = self._sc.binaryFiles(full_path)
- return rdd.values().map(lambda p: pickle.load(BytesIO(p))).collect()[0]
- def load_text_file(self, file_path):
- # TODO, sec problem
- full_path = self._get_full_path(file_path)
- return self._sc.textFile(full_path).collect()
- class SparkStreamingSession(SparkgSession):
- def __init__(self, app_name, ssc_time_window):
- super(SparkStreamingSession, self).__init__(app_name)
- self._ssc = StreamingContext(self._sc, ssc_time_window)
- def get_direct_stream(self, topic, brokers):
- # todo, REMOVE
- return KafkaUtils.createDirectStream(self._ssc, [topic], kafkaParams={"bootstrap.servers": brokers})
- def ready_to_go(self):
- self._ssc.start()
- self._ssc.awaitTermination()
- def __enter__(self):
- return self
- def __exit__(self, e_type, e_value, e_traceback):
- # TODO, sdk support
- print("Detect Error!Error: {}".format(e_type.__name__))
- print("Message: {}".format(e_value.message))
- print("File name: {}".format(e_traceback.tb_frame.f_code.co_filename))
- print("line number: {}".format(e_traceback.tb_lineno))
- self._ssc.stop()
- super(SparkStreamingSession, self).__exit__(e_type, e_value, e_traceback)
补充:
前言
with 语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,比如文件使用后自动关闭/线程中锁的自动获取和释放等。
问题引出
如下代码:
file = open("1.txt")
data = file.read()
file.close()
上面代码存在2个问题:
(1)文件读取发生异常,但没有进行任何处理;
(2)可能忘记关闭文件句柄;
改进
try:
f = open('xxx')
except:
print('fail to open')
exit(-1)
try:
do something
except:
do something
finally:
f.close()
虽然这段代码运行良好,但比较冗长。
而使用with的话,能够减少冗长,还能自动处理上下文环境产生的异常。如下面代码:
with open("1.txt") as file:
data = file.read()
with 工作原理
(1)紧跟with后面的语句被求值后,返回对象的“–enter–()”方法被调用,这个方法的返回值将被赋值给as后面的变量;
(2)当with后面的代码块全部被执行完之后,将调用前面返回对象的“–exit–()”方法。
with工作原理代码示例:
class Sample:
def __enter__(self):
print "in __enter__"
return "Foo"
def __exit__(self, exc_type, exc_val, exc_tb):
print "in __exit__"
def get_sample():
return Sample()
with get_sample() as sample:
print "Sample: ", sample
代码的运行结果如下:
in __enter__
Sample: Foo
in __exit__
可以看到,整个运行过程如下:
(1)enter()方法被执行;
(2)enter()方法的返回值,在这个例子中是”Foo”,赋值给变量sample;
(3)执行代码块,打印sample变量的值为”Foo”;
(4)exit()方法被调用;
【注:】exit()方法中有3个参数, exc_type, exc_val, exc_tb,这些参数在异常处理中相当有用。
exc_type: 错误的类型
exc_val: 错误类型对应的值
exc_tb: 代码中错误发生的位置
示例代码:
class Sample():
def __enter__(self):
print('in enter')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print "type: ", exc_type
print "val: ", exc_val
print "tb: ", exc_tb
def do_something(self):
bar = 1 / 0
return bar + 10
with Sample() as sample:
sample.do_something()
程序输出结果:
in enter
Traceback (most recent call last):
type: <type 'exceptions.ZeroDivisionError'>
val: integer division or modulo by zero
File "/home/user/cltdevelop/Code/TF_Practice_2017_06_06/with_test.py", line 36, in <module>
tb: <traceback object at 0x7f9e13fc6050>
sample.do_something()
File "/home/user/cltdevelop/Code/TF_Practice_2017_06_06/with_test.py", line 32, in do_something
bar = 1 / 0
ZeroDivisionError: integer division or modulo by zero
Process finished with exit code 1
总结
实际上,在with后面的代码块抛出异常时,exit()方法被执行。开发库时,清理资源,关闭文件等操作,都可以放在exit()方法中。
总之,with-as表达式极大的简化了每次写finally的工作,这对代码的优雅性是有极大帮助的。
如果有多项,可以这样写:
With open('1.txt') as f1, open('2.txt') as f2:
do something
参考网址
http://blog.kissdata.com/2014/05/23/python-with.html
spark context stop use with as的更多相关文章
- Spark Context 概述
1. Spark 程序在运行的时候分为 Driver 和 Executor 两部分: 2. Spark 的程序编写是基于 SparkContext 的,具体来说包含两方面: a) Spark 编 ...
- spark 卡在spark context,运行出现spark Exception encountered while connecting to the server : javax.security.sasl.SaslException
原因: 使用root用户运行spark代码 解决方法:使用非管理员账户运行spark即可 [userone@localhost bin]$ ./add-user.sh What type of use ...
- Spark 入门
Spark 入门 目录 一. 1. 2. 3. 二. 三. 1. 2. 3. (1) (2) (3) 4. 5. 四. 1. 2. 3. 4. 5. 五. Spark Shell使用 ...
- (四)Spark集群搭建-Java&Python版Spark
Spark集群搭建 视频教程 1.优酷 2.YouTube 安装scala环境 下载地址http://www.scala-lang.org/download/ 上传scala-2.10.5.tgz到m ...
- Ubuntu安装Hadoop与Spark
更新apt 用 hadoop 用户登录后,我们先更新一下 apt,后续我们使用 apt 安装软件,如果没更新可能有一些软件安装不了.按 ctrl+alt+t 打开终端窗口,执行如下命令: sudo a ...
- 搭建Spark的单机版集群
一.创建用户 # useradd spark # passwd spark 二.下载软件 JDK,Scala,SBT,Maven 版本信息如下: JDK jdk-7u79-linux-x64.gz S ...
- Azure HDInsight 和 Spark 大数据实战(二)
HDInsight cluster on Linux 登录 Azure portal (https://manage.windowsazure.com ) 点击左下角的 NEW 按钮,然后点击 DAT ...
- 在 Azure HDInsight 中安装和使用 Spark
Spark本身用Scala语言编写,运行于Java虚拟机(JVM).只要在安装了Java 6以上版本的便携式计算机或者集群上都可以运行spark.如果您想使用Python API需要安装Python解 ...
- spark的standlone模式安装和application 提交
spark的standlone模式安装 安装一个standlone模式的spark集群,这里是最基本的安装,并测试一下如何进行任务提交. require:提前安装好jdk 1.7.0_80 :scal ...
随机推荐
- 通过ssh登录到手机 Termux
安装Termux Termux官网:https://termux.com/ 安装openssh 安装好Termux后,点击图标进入,依次输入以下命令. 申请读写权限 termux-setup-stor ...
- Java程序运行机制
Java程序运行机制 编译型(compile) 它有一个负责翻译的程序(编译器),将我们写的 Java 源代码转为计算机可执行的代码 举个例子:把一本中文书翻译成英文书 应用:操作系统.C.C++ 解 ...
- tablespace表空间
tablespace——表空间,便于理解,把oracle数据库看作一个实在房间,表空间可以看作这个房间的空间,是可以自由分配,在这空间里面可以堆放多个箱子(箱子可以看作数据库文件),箱子里面再装物件( ...
- Linux 反弹 Shell
攻击场景 Attacker:192.168.0.106 win10 Victim:192.168.2.140 kali NC 反弹 shell Netcat简介 俗称瑞士军刀或NC,小巧强悍,可以读写 ...
- Linux学习-基本命令文件操作
终端 1.多个终端 连接linux的客户端可以理解为终端. 命令:tty查看终端 2.不同终端之间的通讯 [root@wyx wyx]# echo 123 > /dev/pts/1 把123发给 ...
- springcloud使用之服务的注册发现与消费
随着spring的发展我们发现spring提供了越来越多的项目来帮我们简化框架的搭建,使我们站在巨人的肩膀行走,让我们更关注于开发我们的逻辑.随着技术的更替,我们的新项目也逐渐使用了springboo ...
- Python之 time 模块
时间模块的转换关系与方式: #!/usr/bin/env python # -*- coding:utf8 -*- import time # 时间戳 print('\ntime.time() --& ...
- WAMP集成环境虚拟路径修改
只需要改httpd.conf这一个文件就好了. 1.单击右下角wamp图标如下图打开httpd.conf,或者从文件夹打开httpd.conf.
- Shiro集成SSM基于动态URL权限管理(二)
这个案例基于上一个demo扩展而来.所以数据库表,在Shiro集成SSM基于URL权限管理(一)开篇的一致.如果上个demo操作的建议重新导入一次,避免出现问题. 而这次都不是通过固定写在方法上的注解 ...
- oracle中的CURRVAL和NEXTVAL用法
原文:https://blog.csdn.net/qianyiyiding/article/details/51592689 1.什么是sequence?其作用是什么? 在Oracle数据库中,什么 ...