[英]python subprocess module hangs for spark-submit command when writing STDOUT
我有一個python腳本,用於使用spark-submit工具提交spark作業。 我想執行命令並將輸出實時寫入STDOUT和日志文件。 我在ubuntu服務器上使用python 2.7。
這就是我到目前為止的SubmitJob.py腳本
#!/usr/bin/python
# Submit the command
def submitJob(cmd, log_file):
with open(log_file, 'w') as fh:
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
print output.strip()
fh.write(output)
rc = process.poll()
return rc
if __name__ == "__main__":
cmdList = ["dse", "spark-submit", "--spark-master", "spark://127.0.0.1:7077", "--class", "com.spark.myapp", "./myapp.jar"]
log_file = "/tmp/out.log"
exist_status = submitJob(cmdList, log_file)
print "job finished with status ",exist_status
奇怪的是,當我在shell中直接執行同一命令時,它運行良好,並隨着程序的進行在屏幕上產生輸出。
因此,看來我在使用subprocess.PIPE進行stdout和寫入文件時出現了問題。
當前推薦的使用子流程模塊逐行實時寫入stdout和日志文件的方法是什么? 我在互聯網上看到了很多選項,但不確定哪個正確或最新。
謝謝
找出問題所在。 我試圖將兩個stdout n stderr重定向到管道以在屏幕上顯示。 存在stderr時,這似乎會阻止stdout。 如果我從Popen中刪除stderr = stdout參數,則可以正常工作。 因此,對於spark-submit,看起來您不需要顯式重定向stderr,因為它已經隱式執行了此操作
要打印Spark日志,可以調用user330612給定的commandList
cmdList = ["spark-submit", "--spark-master", "spark://127.0.0.1:7077", "--class", "com.spark.myapp", "./myapp.jar"]
然后可以使用子進程進行打印,請記住使用通訊()防止死鎖https://docs.python.org/2/library/subprocess.html警告當使用stdout = PIPE和/或stderr = PIPE和子進程會向管道生成足夠的輸出,從而阻止進程等待OS管道緩沖區接受更多數據。 使用communication()可以避免這種情況。 下面是打印日志的代碼。
import subprocess
p = subprocess.Popen(cmdList,stdout=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
stderr=stderr.splitlines()
stdout=stdout.splitlines()
for line in stderr:
print line #now it can be printed line by line to a file or something else, for the log
for line in stdout:
print line #for the output
有關子流程和打印行的更多信息,請參見: https : //pymotw.com/2/subprocess/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.