如何在 shell 脚本的变量中排除 python 脚本的打印命令



我有一个名为spark.pypython脚本。此 scipt 将在Linux中使用shell脚本调用。

spark.py如下所示:

#!/usr/bin/env python
import sys
import os
if len(sys.argv) != 2:
print "Invalid number of args......"
print "Usage: spark-submit file.py Arguments"
exit()
table=sys.argv[1]
hivedb=sys.argv[2]
from pyspark import SparkContext, SparkConf
conf = SparkConf()
sc = SparkContext(conf=conf)
from pyspark.sql import HiveContext
sqlContext = HiveContext(sc)
from datetime import datetime

df.registerTempTable('mytempTable')
date=datetime.now().strftime('%Y-%m-%d %H:%M:%S')

try:
sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
status = 'fail'
error_message = e
else:  # Executes only if no Exception.
status = 'success'
error_message = 'No error'
print error_message
print ("{},{},{},{},{}".format(hivedb,table,date,status,error_message))
if status != 'success': sys.exit(1)
sc.stop()

shell.sh如下所示

#!/bin/bash
source /home/$USER/source.sh
[ $# -ne 2 ] && { echo "Usage : $0 input file "; exit 1; }
table=$1
hivedb=$2

TIMESTAMP=`date "+%Y-%m-%d"`
touch /home/$USER/logs/${TIMESTAMP}.success_log
touch /home/$USER/logs/${TIMESTAMP}.fail_log
success_logs=/home/$USER/logs/${TIMESTAMP}.success_log
failed_logs=/home/$USER/logs/${TIMESTAMP}.fail_log
#Function to get the status of the job creation
function log_status
{
status=$1
message=$2
if [ "$status" -ne 0 ]; then
echo "$result" | tee -a "${failed_logs}"
else
echo "$result" | tee -a "${success_logs}"
fi
}
result=$(spark-submit --name "Spark" --master "yarn-client" /home/$USER/spark.py ${table} ${hivedb})
g_STATUS=$?
log_status $g_STATUS  "$result"

在此shell脚本中,我将spark.py的输出作为变量收集。当我这样做时,我无法在控制台日志中看到spark.py的任何print命令Linux.

如何在linux console logs中打印所有print命令。

在我的spark.py脚本中,我有

print error_message
print ("{},{},{},{},{}".format(hivedb,table,date,status,error_message))

如何在将输出收集为shell.sh中的变量时排除print error_message

一个简单的方法是将echo "$result"添加到您的 shell 脚本中。您还可以修改 sub 命令以在末尾添加teeresult=$(... | tee /dev/stderr )

我能想到的最干净的方法是创建一个没有print error_messsage的新文件并在shell.sh中使用它......

$ sed '/printserror_message/d' "/home/${USER}/spark.py" > "/home/${USER}/spark_no_err_msg.py"

最新更新