使用子进程命令循环遍历文件的变量列表时出现 TypeError

TypeError while looping through a variable list of files with subprocess commands

作为背景,我创建了一个列表,其中包含不同文件名的元素,其完整路径 (/.../filea.dat) 称为 fileList,它的长度可变。它的形式为 fileList = ['/../filea.dat', '/../fileb.dat'].

我想对该文件列表中的每个文件执行子进程命令,然后分别分析每个文件(和生成的新文件)的组件。

for i, elem in enumerate(fileList):
   hexed = fileList[i]
   subprocess.Popen("hexdump " + hexed + " > hexed.dat", shell=True)

   with open("hexed.dat", "r") as f:
      for line in f:
         if "statement" in line:
            value = "examplevalue"
   if value == "examplevalue"
      other subprocess statements that create a file that will again be used later

现在我有一个TypeError: cannot concatenate 'str' and 'list' objects。让我知道我是否也在使用这种方法的正确轨道上。

如果我需要提供额外的说明,请告诉我;我试图简化到基础知识,因为其他细节对问题并不重要。

你很接近。您收到类型错误是因为 Popen 要求您在传入字符串而不是列表时还设置 shell=True 。但还有另一个问题:Popen 不会等待进程完成,因此当您读取文件时,其中还没有任何有用的信息。一种不同的策略是跳过文件重定向并直接读取输出流。另请注意,您不需要使用 enumerate... for 循环已获取列表中的值。我们可以跳过 shell 并将命令作为列表传递。

for hexed in fileList:
    proc = subprocess.Popen(["hexdump", hexed], stdout=subprocess.PIPE,
        stderr=open(os.devnull, 'w'))
    for line in proc.stdout:
        if "statement" in line:
            value = "examplevalue"
    proc.wait()
    if proc.returncode != 0:
        print('error') # need less lame error handling!   
    if value == "examplevalue"
        other subprocess statements that create a file that will again be