Home > front end >  Stop the command when find a string - python
Stop the command when find a string - python

Time:02-25

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?

CodePudding user response:

The line for line in ls isn't doing what you think it is. Instead of going line by line, it's going through ls character by character. What you want to have is for line in ls.splitlines(). You can then check if main.py is on that line by calling "main.py" in line

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.splitlines():
  print(line)

  #if find main.py print stop and exit
  if "main.py" in line:  
    print('stop...')
    exit()

That should be more what you want I think.

You're also printing ls every loop, which you need to change to only print the current line

CodePudding user response:

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 
  • Related