python子进程输出被截断

时间:2017-12-09 23:19:55

标签: python linux subprocess ps

使用子进程在python中运行shell命令时输出错误。

bash shell中的

grep( com.vertica.solutions.kafka.Launcher

ps -ef | grep com.vertica.solutions.kafka.Launcher
root      92300  39024  0 23:06 pts/1    00:00:00 grep --color=auto  com.vertica.solutions.kafka.Launcher
dbadmin  413872 413868  0 22:06 pts/0    00:00:24 java -cp /opt/vertica/packages/kafka/bin/../lib/*:/opt/vertica/java/lib/vertica-jdbc.jar:/opt/vertica/packages/kafka/bin/../config/* -Dlog4j.configurationFile=/opt/vertica/packages/kafka/bin/../config/vkafka-log-config.xml -DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector com.vertica.solutions.kafka.Launcher --conf /home/dbadmin/live.conf
python shell中的

grep( com.vertica.solutions.kafka.Launcher

>>> cmd = "ps aux |grep com.vertica.solutions.kafka.Launcher| grep -v grep"
>>> check_output(cmd,shell=True).strip()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/subprocess.py", line 575, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command 'ps aux |grep com.vertica.solutions.kafka.Launcher| grep -v grep' returned non-zero exit status 1

这是因为子进程正在截断ps输出。当我用单词kafka grep时,我得到了结果,但它不是所希望的。

grep only kafka

>>> cmd = "ps aux | grep kafka | grep -v grep"
>>> check_output(cmd,shell=True).strip()
dbadmin  413868  0.0  0.0 113128  1372 pts/0    S    22:06   0:00   /bin/bash /opt/vertica/packages/kafka/bin/vkconfig launch --conf /home/dbadmin/live.conf\n
dbadmin  413872  0.6  1.0 7403000 175544 pts/0  Sl   22:06   0:25 java -cp /opt/vertica/packages/kafka/bin/../lib/*:/opt/vertica/java/lib/vertica-jdbc.jar:/opt/vertica/package'
  
    
      

    
  

当我只用单词kafka grep时,我得到进程(pid 413872),但在python shell中,进程命令的COMMAND列输出不完整。

1 个答案:

答案 0 :(得分:0)

子进程不是truncating无论将哪些内容写入stdout,都会通过管道进入你的python会话。会发生什么是-v没有成功,所以退出时返回错误代码(无零)。

要忽略您没有从grep获得任何输出的情况,您可以执行以下操作:

import os
from subprocess import Popen

DEVNULL = open(os.devnull, 'wb')
cmd = 'ps aux |grep com.vertica.solutions.kafka.Launcher| grep -v grep' 
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=DEVNULL, shell=True)
print process.communicate()[0] #output 

这将确保,如果grep没有成功,而不是返回错误代码,它将只是转储它。