Python Forum
Subprocess - get only first few lines of stdout
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Subprocess - get only first few lines of stdout
#1
Hello all. I am using subprocess module to execute a process and read stdout returned by it. Currently my code saves all the lines of stdout to a list ("lines" in the code below). However, I am interested only in first 3 lines of the stdout. The only way I managed to get first 3 lines was by simply taking first 3 items from the list. But I am wondering whether there is a more elegant and efficient way. One which would only have subprocess "extract" a specific number of stdout lines already to start with? Thanks. JC

process = subprocess.Popen("top -n 1", stdout=subprocess.PIPE, shell=True)
output = process.stdout.read()
output_lines = output.split(b'\n')
lines = []
Reply


Messages In This Thread
Subprocess - get only first few lines of stdout - by j.crater - May-30-2017, 11:39 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [subprocess] Why stdout sent to stderr? Winfried 3 595 Jan-26-2024, 07:26 PM
Last Post: snippsat
  Performance options for sys.stdout.writelines dgrunwal 11 3,348 Aug-23-2022, 10:32 PM
Last Post: Pedroski55
  Did subprocess.Popen() causes main routine to pause stdout? liudr 4 3,761 May-04-2021, 08:58 PM
Last Post: liudr
  changing stdout and stderr Skaperen 4 2,807 Dec-02-2020, 08:58 PM
Last Post: Skaperen
  Get stdout of a running process yok0 0 3,148 Aug-20-2020, 10:12 AM
Last Post: yok0
  Iterate 2 large text files across lines and replace lines in second file medatib531 13 6,179 Aug-10-2020, 11:01 PM
Last Post: medatib531
  will with sys.stdout as f: close sys.stdout? Skaperen 9 4,791 Nov-03-2019, 07:57 AM
Last Post: Gribouillis
  Add stdout to text file maxtimbo 3 3,249 Feb-05-2019, 12:53 AM
Last Post: maxtimbo
  stdout buffering Skaperen 5 4,844 Jun-12-2018, 06:14 AM
Last Post: Skaperen
  stdout Skaperen 0 2,703 Mar-19-2018, 01:23 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020