Reputation: 1
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
Reputation: 140266
Preamble:
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
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