-2

I use list comprehension for simple loops. But I could't use list comprehension for the following code. How can I do it?

import psutil
list1 = []
for pr in psutil.process_iter():
    with pr.oneshot():
        list1.append([pr.name(), pr.status()])

Python 3.8
oduncu90
  • 45
  • 8
  • 5
    you don't have to always use list comprehension. sometimes is just better not to. if that works, don't be too keen to change it – Have a nice day Feb 23 '21 at 17:57
  • 3
    Please read https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ . Some constructs, like `with` and `try`, cannot be replicated with a list comprehension. – Karl Knechtel Feb 23 '21 at 17:58
  • 1
    don't use `list` as your variable name, it's a Python built-in. – Vishal Singh Feb 23 '21 at 17:59
  • I have updated the first post. It is a simplied version of the actual code. It had some mistakes. – oduncu90 Feb 23 '21 at 18:03
  • you need to make a function that do the stuff that can't be put in a cromprehension like with or try construct – Copperfield Feb 23 '21 at 18:24

1 Answers1

1

I don't recommend it, but technically you could use the following code to turn the for-loop into a list comprehension:

from contextlib import ExitStack

with ExitStack() as stack:
    list1 = [
        (tmp := [pr.name(), pr.status()]) and stack.close() or tmp
        for pr in psutil.process_iter()
        for pr in [stack.enter_context(pr.oneshot()), pr][1:]
    ]
del tmp
a_guest
  • 34,165
  • 12
  • 64
  • 118
  • It works. Are there any ways for improving the performance (lower cpu usage)? I am using this code in a loop (repeats less than a second). Very very small improvements (less than %1 usage gains) also could be accepted. It could be like your method in the answer or in a different way (without using list comprehension). – oduncu90 Feb 24 '21 at 04:14
  • 1
    @oduncu90 This answer was added for educational purposes, to show how complex it is to replicate the simple structure of the `for` loop as a list comprehension. I didn't benchmark the code, but I expect the comprehension to be slower since it has to create a few temporary objects and name bindings. So you really should be using the original code from your question, it's also much more readable. – a_guest Feb 24 '21 at 07:57