2

I would like to create python3 code to filter system processes by running the linux command 'ps'.

Here is my current code:

import subprocess,tempfile
command='ps -fe | grep java'
f = tempfile.NamedTemporaryFile(delete=False)
run = subprocess.Popen([command],shell=True,stdout=f)
f.name

'/tmp/tmpswfw1_c8'

By running above code, we get a file containing the ps list, which has a 'java' entry in it. But when I cat the file, the long lines get cut. E.g. if the real process line is:

tomcat   21294     1 41 Jul06 ?        1-14:29:27 /opt/java/bin/java -Xms4096m -Xmx4096m -jar /opt/microservices/apps-0.0.1-SNAPSHOT.jar --spring.profiles.active=staging

this line is being processed into that tempfile by python as:

tomcat   21294     1 41 Jul06 ?        1-14:29:27 /opt/java/bin/java -Xms4096m -Xmx4096m -jar /opt/microservices/apps[[other_chars_are_missing_here]]

The width in output file is same with the width in terminal when I run the python code.

How to correctly get the real output of ps?

Edited by adding:

And I also get same truncated line with subprocess.check_output:

print (subprocess.check_output("ps -fe | grep java", shell=True))

Xizhen Du
  • 31
  • 3
  • this is a duplicate of https://stackoverflow.com/questions/1996518/retrieving-the-output-of-subprocess-call/21000308 – AntiMatterDynamite Jul 10 '18 at 13:08
  • @AntiMatterDynamite I think this is not a same question. I am able to get output, but some long lines in the output are being truncated. – Xizhen Du Jul 11 '18 at 01:44
  • then it could be a grep problem with environment variables, look in `os.environ' it might have something that tells grep to truncate itself – AntiMatterDynamite Jul 11 '18 at 06:20

1 Answers1

0

I believe that this is actually an issue with ps, not with Python. Try:

print(subprocess.check_output("ps -fe --width 1000 | grep java", shell=True))

or

print(subprocess.check_output("ps -wwfe | grep java", shell=True))
Oliver Evans
  • 1,405
  • 14
  • 17
  • 1
    Thanks Oliver. It resolves the issue. But the command 'ps -fe | grep java' in bash/shell can output the correct lines in terminal or file, I can't understand how python truncate it when it gets these input from the upstream(ps or shell)? – Xizhen Du Jul 11 '18 at 02:59
  • Glad I could help. I've been frustrated by this issue before, and don't understand quite why it happens. – Oliver Evans Jul 11 '18 at 03:04