How to pass the execution result of a shell command in a list in Python (non-blocking version)

In How to pass the execution result of shell command in Python as a list, there was such a source. This is a good idea, but it's a shame to wait for the shell command to finish.

res_cmd_no_lfeed.py


#!/usr/bin/python

import subprocess

def res_cmd_lfeed(cmd):
  return subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).stdout.readlines()

def res_cmd_no_lfeed(cmd):
  return [str(x).rstrip("\n") for x in res_cmd_lfeed(cmd)]

def main():
  cmd = ("ls -l")
  print(res_cmd_no_lfeed(cmd))

if __name__ == '__main__':
  main()

So use yield

res_cmd_no_lfeed.py


#!/usr/bin/python

import subprocess

def res_cmd_lfeed(cmd):  #The return value is not a list but each line
  for line in subprocess.Popen(cmd, stdout=subprocess.PIPE,shell=True).stdout:
      yield line

def res_cmd_no_lfeed(cmd):
  return [str(x).rstrip("\n") for x in res_cmd_lfeed(cmd)]

def main():
  cmd = ("ls -l")
  print(res_cmd_no_lfeed(cmd))

if __name__ == '__main__':
  main()

res_cmd_lfeed does not block until the end of the command, but returns a yield when it receives a line in the loop, that is, it stops the loop and returns the result at that time. If you are told "Next," it will resume and return the next result ... and so on.

In this example, res_cmd_no_lfeed waits until all the Arrays are completed, so it doesn't make sense. If it's a web application, you can steadily return a response to the browser.

What are you happy about

forevertime.bat


@echo off
:TOP
echo %time%
goto top

You can see it by doing something like this. Since this batch file keeps outputting indefinitely, the former source keeps waiting with readlines (), but the latter captures and processes the result more and more. Like "Tear off and throw".

Caution. The pipe has a buffer

forevertime.bat(Mass output version)


@echo off
:TOP
set /P X=0123456789012345678901234567890123456789012345678901234567890123<NUL
set /P X=0123456789012345678901234567890123456789012345678901234567890123<NUL
set /P X=0123456789012345678901234567890123456789012345678901234567890123<NUL
set /P X=0123456789012345678901234567890123456789012345678901234567890123<NUL
set /P X=0123456789012345678901234567890123456789012345678901234567890123<NUL
set /P X=0123456789012345678901234567890123456789012345678901234567890123<NUL
set /P X=0123456789012345678901234567890123456789012345678901234567890123<NUL
set /P X=0123456789012345678901234567890123456789012345678901234567890123<NUL
echo %time%
goto top

I think I can tune more and more, but I wonder if I should leave it here.

Recommended Posts

How to pass the execution result of a shell command in a list in Python (non-blocking version)
How to pass the execution result of a shell command in a list in Python
[sh] How to store the command execution result in a variable
How to get a list of files in the same directory with python
How to get the last (last) value in a list in Python
How to get a list of built-in exceptions in python
How to check in Python if one of the elements of a list is in another list
How to determine the existence of a selenium element in Python
How to check the memory size of a dictionary in Python
How to update the python version of Cloud Shell on GCP
linux / c> link> Get the execution result of the shell command in the C program> I was taught how to use popen ()
How to clear tuples in a list (Python)
Make a copy of the list in Python
[Python] How to put any number of standard inputs in a list
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[Linux] Command to get a list of commands executed in the past
How to format a list of dictionaries (or instances) well in Python
How to get the number of digits in Python
A memorandum of how to execute the! Sudo magic command in Jupyter Notebook
How to execute a command using subprocess in Python
How to count the number of occurrences of each element in the list in Python with weight
How to find the first element that matches your criteria in a Python list
[Python] How to make a list of character strings character by character
How to shuffle a part of a Python list (at random.shuffle)
How to use the __call__ method in a Python class
Get the number of specific elements in a python list
How to develop in a virtual environment of Python [Memo]
How to connect the contents of a list into a string
In the python command python points to python3.8
How to get the Python version
[Golang] Command to check the supported GOOS and GOARCH in a list (Check the supported platforms of the build)
Get the value of a specific key up to the specified index in the dictionary list in Python
[Python] How to delete rows and columns in a table (list of drop method options)
[OCI] Python script to get the IP address of a compute instance in Cloud Shell
How to quickly count the frequency of appearance of characters from a character string in Python?
How to pass arguments to a Python script in SPSS Modeler Batch
Try to get a list of breaking news threads in Python.
How to get a string from a command line argument in python
[Introduction to Python] How to use the in operator in a for statement?
[Python3] Define a decorator to measure the execution time of a function
How to delete multiple specified positions (indexes) in a Python list
[Python] A program that rotates the contents of the list to the left
How to check the version of Django
[Python] How to convert a 2D list to a 1D list
Display a list of alphabets in Python 3
The result of installing python in Anaconda
How to get a stacktrace in python
How to check opencv version in python
[Python / Tkinter] How to pass arguments to command
Summary of how to use Python list
How to hide the command prompt when running python in visual studio 2015
How to send a visualization image of data created in Python to Typetalk
I want to batch convert the result of "string" .split () in Python
I want to sort a list in the order of other lists
Receive a list of the results of parallel processing in Python with starmap
I want to leave an arbitrary command in the command history of Shell
I made a program to check the size of a file in Python
How to sort by specifying a column in the Python Numpy array.
[Completed version] Try to find out the number of residents in the town from the address list with Python
How to use the C library in Python
How to receive command line arguments in Python