subprocess.Popen:在通过crontab运行时不返回完整输出

问题描述 投票:0回答:2

我在包含在python脚本中的unix环境中调用了一些java二进制文件

当我从bash调用脚本时,输出变得干净并且也存储在所需的变量中,但是当我从Cron运行相同的脚本时,存储的输出(在变量中)是不完整的

我的代码:

command = '/opt/HP/BSM/PMDB/bin/abcAdminUtil -abort -streamId ETL_' \
          'SystemManagement_PA@Fact_SCOPE_OVPAGlobal'
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, 
                       stderr=subprocess.PIPE)
(output, err) = proc.communicate() # Storing Output in output variable

从shell运行时输出变量的值:

Abort cmd output:PID:8717
Executing abort function
hibernateConfigurationFile = /OBRHA/HPE-OBR/PMDB/lib/hibernate-core-4.3.8.Final.jar
Starting to Abort Stream ETL_SystemManagement_PA@Fact_SCOPE_OVPAGlobal
Aborting StreamETL_SystemManagement_PA@Fact_SCOPE_OVPAGlobal

从cron运行时输出变量的值:

PID:830

看来输出创建新进程后没有存储在变量里面,我不知道为什么?

linux python-2.7 shell subprocess cron-task
2个回答
0
投票

Kintul。

你的问题似乎与这个问题非常相似:Capture stdout stderr of python subprocess, when it runs from cron or rc.local

看看这对你有帮助。


0
投票

发生这种情况是因为Java实用程序正在抛出异常,而不是由subprocess.Popen缓存

但是,subprocess.check_output会捕获异常

更新的代码:

try:
    output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
except subprocess.CalledProcessError as exc:
    print("Status : FAIL", exc.returncode, exc.output)
else:
    print("Output of Resume cmd: \n{}\n".format(output))
    file.write("Output of Resume cmd: \n{}\n".format(output) + "\n") 

输出代码:

('Status : FAIL', -11, 'PID:37319\n')
('Status : FAIL', -11, 'PID:37320\n')

因此,命令抛出异常由subprocess.check_output缓存,而不是由subprocess.Popen缓存

解压缩subprocess.check_output的官方页面

如果返回码非零,则会引发CalledProcessError。 CalledProcessError对象将具有returncode属性中的返回代码以及output属性中的任何输出。

© www.soinside.com 2019 - 2024. All rights reserved.