简体   繁体   English

如何避免对同一文件执行操作的for循环重复?

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

Python noob in the house (yet): 房子里的Python noob(尚未):

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. 主要问题是,如果找不到该文件,则chmod可能会失败,然后,对我来说,剩下的第二条命令浪费时间。

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. 因此,我可以在给定列表上运行chmod,然后进行第二次迭代以执行shell脚本命令。

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 /*" ?) . 请注意,不建议使用os.system并存在安全问题,尤其是在您的上下文中(如果其中一行包含"somefile; rm -rf /*" )。 You should use subprocess.call 您应该使用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... 从文件逐行传递项目需要您rstrip或换rstrip命令中,它将100%的时间失败...

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): 现在,如果命令的返回码不是0(除了最后一条命令,那没关系),您可以使用continue跳过当前项:

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()])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM