MERCUR
MERCUR

Reputation: 1

How do I avoid for loop repetition for action on the same file?

Python noob in the house (yet):

I am handling a file line by line like:

import os

with open ('data.txt','r') as f:
    for line in f:
        os.system("/bin/chmod -x {}".format(line))
        os.system("/usr/bin/clipass {}".format(line))

The main problem is that chmod can fail if the file was not found, and then, for me,the remaining second command is waste of time.

What is the best practice to divide the action in two (besides repeating the loop twice). So I could run chmod on the given list and then make the second iteration to perform the shell script command.

Upvotes: 0

Views: 137

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140266

Preamble:

  • note that os.system is deprecated and has security issues, specially in your context (what if one of the lines has "somefile; rm -rf /*" ?) . You should use subprocess.call
  • passing items from a file line-by-line requires you to rstrip or the linefeed is in the command and it will fail 100% of the time...

Now, you could use continue to skip the current item if return code of the command isn't 0 (except for the last command, where it doesn't matter):

with open ('data.txt','r') as f:
    for line in f:
        if subprocess.call(["/bin/chmod","-x",line.rstrip()])
           continue
        subprocess.call(["/usr/bin/clipass",line.rstrip()])

Upvotes: 1

Related Questions