Search code examples
pythonsubprocesspython-regnu-screenfindall

Python re.findall expected string


I want to search for a word in my string with re.findall. The Code is the following:

def check_status():
   p1 = subprocess.run(["screen", "-ls"], shell=False)
   p2 = re.findall("myscreen", p1)
   print(p2)

The return from p1 looks like this:

There are screens on:
    2420454.myscreen        (12/25/2021 01:15:17 PM)        (Detached)
    6066.bot                (12/14/2021 07:11:52 PM)        (Detached)

If I execute this function, I get the following error message:

File "/usr/lib/python3.10/re.py", line 240, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object

I searched for this problem already but found nothing.

I'm using Python 3.10


Solution

  • subprocess.run returns a CompletedProcess object. You want to add capture_output=True and text=True to the keyword arguments, and apply the regular expression to its stdout member:

    p2 = re.findall('myprocess', p1.stdout)
    

    .. though of course, you don't need a regular expression to look for a static string:

    p2 = 'myprocess' in p1.stdout
    

    If you want to extract the screen ID, maybe loop over stdout.splitlines() and extract the first token from the matching lines.

    p2 = []
    for line in p1.stdout.splitlines():
        if 'myprocess' in line:
            p2.append(line.split('.')[0]