首页 > 解决方案 > 我希望 Python 处理目录中的所有 xml 文件,但它只处理最上面的文件

问题描述

我有一个最初打算与单个文件一起使用的 xml 解析器,但经过编辑以处理给定目录和通配符的目录中的所有文件。它是从 Linux 服务器运行的。该命令遵循以下用法:

-d, --directory 一次读取所有文件的目录;示例 -d /output/*.xml

-f, --file xml 读入;示例:-f output.xml

-o, --output HTML 报告的输出文件的文件名

所以,在这个特定的例子中,我正在尝试做的一个例子将被写成

python parser.py -d /目录/目录 -w 输出*.xml

这是我的主要()

def main():
     if (output != ''):
         if output.endswith('.html'):
             outFile = open(output, 'w')
         else:
             outFile = open(output + '.html', 'w')
     else:
         outFile = open('nmap-SMB-scan-output.html', 'w')

     if (inFile != ''):
         if not os.path.isfile(inFile):
             print('\nThere was an error opening file: %s (1)' % inFile)
             sys.exit()
         else:
             try:
                 outFile = header(outFile)
                 outFile = processFile(inFile, outFile)
                 outFile = footer(outFile)
             except:
                 print('\nThere was an error opening file: %s (2)' % inFile)

     elif (directory != ''):
         if (wildcard == ''):
             print('\nExiting, if using directory must use wildcard as well.')
             sys.exit()
         findFiles = directory + '/' + wildcard
         onlyfiles = glob.glob(findFiles)
         outFile = header(outFile)
         for f in onlyfiles:
             try:
                 outFile = processFile(f, outFile)
             except:
                 print('\nThere was an error opening file: %s (3)' % f)
         outFile = footer(outFile)

     else:  # if (inFile = '') and (directory = ''):
         print('\nYou must provide a file or directory to continue.')
         sys.exit()

然后文件被踢到实际的处理方面,被格式化,并点击这个 try 语句:

try:
     opts, args = getopt.getopt(sys.argv[1:], "f:o:w:d:", ['file=', 'output=', 'wildcard=', 'directory='])
     inFile = output = directory = wildcard = ''
     proceed = False
     for opt, val in opts:
         if opt in ('-f', '--file'):
             if not os.path.isfile(val):
                 print('\nFile "%s" does not appear to exist, please verify file name.' % val)
                 sys.exit()
             else:
                 proceed = True
             inFile = val
         if opt in ('-o', '--output'):
             output = val
         if opt in ('-d', '--directory'):
             if not os.path.isdir(val):
                 print('\nDir "%s" does not appear to exist, please verify directory name.' % val)
                 sys.exit()
             else:
                 print("Directory selection:" + % val)
                 proceed = True
                 directory = val
         if opt in ('-w', '--wildcard'):
             wildcard = val

     if (__name__ == '__main__') and proceed == True:
         main()
     else:
         print('Need to provide a file or directory to process')
         usage()

 except getopt.error:
     usage()

我不太确定为什么它不循环回到 main() 以继续下一个文件...您可以提供的任何建议将不胜感激。

标签: pythonxmllinux

解决方案


推荐阅读