How to pass the execution result of a shell command in a list in Python

Introduction

If you want to handle shell commands in Python, you generally use the subprocess module. It is possible to pass the result as a list by using stdout.readlines () in the module, but if the shell command to be executed spans multiple lines, the line feed code (line feed) will be passed together. Therefore, in order to pass the list with the line feed code (line feed) removed, the following processing should be performed.

Here, we will explain using an example of executing ls -l from Python as a shell command.

This time, I created three scripts according to the following three ways.

Actually, the result sample when ls -l is executed is as follows.

$ ls -l
total 12
-rwxr-xr-x 1 root root 260 Jun 16 18:48 res_cmd_lfeed.py
-rwxr-xr-x 1 root root 378 Jun 16 18:49 res_cmd_no_lfeed.py
-rwxr-xr-x 1 root root 247 Jun 16 18:48 res_cmd.py

To get the same result as the shell execution

Get the first array element of communicate ().

res_cmd.py


#!/usr/bin/python

import subprocess

def res_cmd(cmd):
  return subprocess.Popen(
      cmd, stdout=subprocess.PIPE,
      shell=True).communicate()[0]

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

if __name__ == '__main__':
  main()

As shown below, the execution result of the script is the same as when ls -l is executed.

$ ./res_cmd.py
total 12
-rwxr-xr-x 1 root root 260 Jun 16 18:48 res_cmd_lfeed.py
-rwxr-xr-x 1 root root 378 Jun 16 18:49 res_cmd_no_lfeed.py
-rwxr-xr-x 1 root root 247 Jun 16 18:48 res_cmd.py

To get a list with line feed

Use stdout.readlines ().

res_cmd_lfeed.py


#!/usr/bin/python

import subprocess

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

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

if __name__ == '__main__':
  main()

You can get a list of results that include line feeds.

$ ./res_cmd_lfeed.py
['total 12\n', '-rwxr-xr-x 1 root root 261 Jun 16 18:52 res_cmd_lfeed.py\n', '-rwxr-xr-x 1 root root 380 Jun 16 18:52 res_cmd_no_lfeed.py\n', '-rwxr-xr-x 1 root root 248 Jun 16 18:51 res_cmd.py\n']

To get a list without line feed

Use stdout.readlines () and rstrip ("\ n") in list comprehensions.

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()

You can get a list of results excluding line feed.

$ ./res_cmd_no_lfeed.py
['total 12', '-rwxr-xr-x 1 root root 261 Jun 16 18:52 res_cmd_lfeed.py', '-rwxr-xr-x 1 root root 380 Jun 16 18:52 res_cmd_no_lfeed.py', '-rwxr-xr-x 1 root root 248 Jun 16 18:51 res_cmd.py']

Recommended Posts

How to pass the execution result of a shell command in a list in Python
How to pass the execution result of a shell command in a list in Python (non-blocking version)
[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 identify the element with the smallest number of characters in a Python list?
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 variable in Python
How to check the memory size of a dictionary in Python
How to output the output result of the Linux man command to a file
How to clear tuples in a list (Python)
Make a copy of the list in Python
linux / c> link> Get the execution result of the shell command in the C program> I was taught how to use popen ()
[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
How to write a list / dictionary type of Python3
How to execute a command using subprocess in Python
[Python] How to output the list values in order
A memorandum of how to execute the! Sudo magic command in Jupyter Notebook
In the python command python points to python3.8
[Python] How to make a list of character strings character by character
Measure the execution result of the program in C ++, Java, Python.
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
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
[Golang] Command to check the supported GOOS and GOARCH in a list (Check the supported platforms of the build)
How to pass arguments to a Python script in SPSS Modeler Batch
How to know the internal structure of an object in Python
Try to get a list of breaking news threads in Python.
[Python] How to convert a 2D list to a 1D list
Display a list of alphabets in Python 3
Get the value of a specific key up to the specified index in the dictionary list in Python
How to get a string from a command line argument 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
[Introduction to Python] How to use the in operator in a for statement?
The result of installing python in Anaconda
How to get a stacktrace in python
How to quickly count the frequency of appearance of characters from a character string in Python?
[Python3] Define a decorator to measure the execution time of a function
How to monitor the execution status of sqlldr with the pv command
How to get the vertex coordinates of a feature in ArcPy
[Python / Tkinter] How to pass arguments to command
Summary of how to use Python list
How to update the python version of Cloud Shell on GCP
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 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