'Stop the command when find a string - python

I want to print a command until it finds the main.py file and then stops.

I tried this code but according to logic it is printing the code several times and not line by line until I stop at mine where I find the main.py file.

import subprocess

#store ls -l to variable
get_ls = subprocess.getoutput("ls -l")

#transfom output to string
ls = str(get_ls)

#search for main.py file in ls
for line in ls:
  main_py = line.find('main.py')
  print(ls)

  #if find main.py print stop and exit
  if main_py == 'main.py':  
    print('stop...')
    exit()
    

Output is looping this:

-rw-r--r-- 1 runner runner 9009 Feb 19 19:00 poetry.lock
-rw-r--r-- 1 runner runner  354 Feb 19 19:00 pyproject.toml
-rw-r--r-- 1 runner runner  329 Feb 25 00:10 main.py
-rw-r--r-- 1 runner runner  383 Feb 14 17:57 replit.nix
-rw-r--r-- 1 runner runner   61 Feb 19 18:46 urls.tmp
drwxr-xr-x 1 runner runner   56 Oct 26 20:53 venv

I want this output:

-rw-r--r-- 1 runner runner 9009 Feb 19 19:00 poetry.lock
-rw-r--r-- 1 runner runner  354 Feb 19 19:00 pyproject.toml
-rw-r--r-- 1 runner runner  329 Feb 25 00:10 main.py
###### stops here #######

How to fix this?



Solution 1:[1]

In my opinion, if you only want to achieve the result and don’t mind changing your logic, this the most elegant, and which is the most "pythonic" one. I like the simplicity of the os.walk() method:

import os

for root, dirs, files in os.walk("."):
    for filename in files:
        print(filename)
        
        if filename == "main.py":
            print("stop")
            break 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jcunhafonte