简体   繁体   中英

How to get one line from a subprocess.call in python

I'm trying to pull one line from a subprocess.call but so far I'm having no luck. I want to do this with a number of different subprocess.calls but here is one for example:

output = subprocess.call('vmstat -s, shell=True)

The vmstat -s simple returns a list of current memory status. I could like to read say line 2 (used memory) and store it in a variable for later use.

What is the best way to go about this in python?

Thank You

Use check_output instead of call :

>>> subprocess.check_output('vmstat -s', shell=True).splitlines()

alternatively you can pipe stdout :

>>> from subprocess import Popen, PIPE
>>> for line in Popen('vmstat -s', shell=True, stdout=PIPE).stdout:
...     print(line)
... 
b'      3717436 K total memory\n'
b'      2151640 K used memory\n'
b'      1450432 K active memory\n'
...

The usual way to read from a subprocess stdout is with the communicate method.

>>> from subprocess import Popen, PIPE
>>> proc = Popen(['vmstat', '-s'], stdout=PIPE, stderr=PIPE)
>>> stdout, _stderr = proc.communicate()
>>> stdout.splitlines()[1]
'     13278652 K used memory'

Note that using shell=True isn't needed here, and its use is generally discouraged when not required (there is unnecessary overhead, and it can create a shell injection security vulnerability in certain situations).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM