2016-09-20 171 views
0

首先,我假设我们已经设置了SPARK_HOME,在我的情况下它是~/Desktop/spark-2.0.0。基本上,我想使用Cronjob运行我的PySpark脚本(例如crontab -e)。我的问题是如何添加环境路径使Spark脚本与Cronjob一起工作。这里是我的示例脚本,example.py使用Cronjob运行PySpark(crontab)

import os 
from pyspark import SparkConf, SparkContext 

# Configure the environment 
if 'SPARK_HOME' not in os.environ: 
    os.environ['SPARK_HOME'] = '~/Desktop/spark-2.0.0' 

conf = SparkConf().setAppName('example').setMaster('local[8]') 
sc = SparkContext(conf=conf) 

if __name__ == '__main__': 
    ls = range(100) 
    ls_rdd = sc.parallelize(ls, numSlices=10) 
    ls_out = ls_rdd.map(lambda x: x+1).collect() 

    f = open('test.txt', 'w') 
    for item in ls_out: 
     f.write("%s\n" % item) # save list to test.txt 

run_example.sh我的bash脚本如下

rm test.txt 

~/Desktop/spark-2.0.0/bin/spark-submit \ 
    --master local[8] \ 
    --driver-memory 4g \ 
    --executor-memory 4g \ 
    example.py 

在这里,我想用crontab运行run_example.sh每分钟。但是,当我运行crontab -e时,我不知道如何自定义路径。到目前为止,我只看到这Gitbook link。我在我的Cronjob编辑器中没有运行我的代码。

#!/bin/bash 

# add path to cron (this line is the one I don't know) 
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$HOME/anaconda/bin 

# run script every minutes 
* * * * * source run_example.sh 

在此先感谢!

回答

2

你可以做的是在home位置的.bashrc文件中添加以下行。

export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$HOME/anaconda/bin 

,那么你可以在crontab中以下条目

* * * * * source ~/.bashrc;sh run_example.sh 

这条线将首先执行你的.bashrc文件,这将设置PATH值,那么它会执行run_example.sh

或者,您可以只在run_example.sh中设置PATH,

export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$HOME/anaconda/bin 
rm test.txt 

~/Desktop/spark-2.0.0/bin/spark-submit \ 
    --master local[8] \ 
    --driver-memory 4g \ 
    --executor-memory 4g \ 
    example.py 
+0

非常感谢@Sarwesh!基本上,'source〜/ .bashrc'就是我正在寻找的东西。我之前并不知道我们可以在一行中运行多个bash shell! – titipata