首页 > 解决方案 > 使用 subprocess.Popen 时的文件处理问题

问题描述

我无法读取由 subprocess.Popen 创建的标准输出文件。我检查了文件是否正确创建。当我在另一个函数中尝试处理它时,就会出现这个问题。在 loopback_test 函数中,print(lines) 打印一个空列表 [],如果我同时调用这两个函数(write_dump() 和 loopback_test()),print(line) 不会打印任何内容。如果我注释掉 write_dump() 函数 loopback_test() 按预期工作。在调用 subprocess.Popen 之后我需要做些什么吗?

我试过的东西:

subprocess.Popen(['cmd, arg1, arg2],stdout = out)
out.flush() 
with open("filename.txt","r") as out:   

创建文件后,如果我将“w+”替换为“r”,loopback_test() 函数将按预期工作。但这不是我想要的。如果文件不存在,我需要创建它。

def write_dump():                                                                                        
   with open("filename.txt","w+") as out:                                                                
                                                                                                         
      subprocess.Popen(['cmd, arg1, arg2],stdout = out)             
                                                                                                         
                                                                                                         
def loopback_test():                                                                                     
   with open("filename.txt", 'r') as infile:                                                             
       lines = infile.readlines()                                                                        
       print(lines)                                                                                                    
                                                                                                         
   with open("filename.txt", 'w') as outfile:                                                            
      for pos, line in enumerate(lines):                                                                 
         if not line.startswith('{"GET":'):                                                              
            print(line)                                                                                  
            outfile.write(line)                                                                          
                                                                                                         
   with open("filename.txt", 'r') as read_file:                                                          
      data = json.load(read_file)                                                                        
      for k,v in data['state']['configs']['lps_control'].items():                                        
         if(k == 'cal'):                                                                                 
            print(v)  



write_dump()
loopback_test()                                                                                   
                                                                                                         

标签: pythonsubprocessfile-handlingpopen

解决方案


推荐阅读