Python 3.x For循环未在Python脚本中运行,以循环函数中的dictionary对象

Python 3.x For循环未在Python脚本中运行,以循环函数中的dictionary对象,python-3.x,csv,Python 3.x,Csv,我有下面的Python脚本(请原谅我的粗心大意的编码),我有一个奇怪的问题。下面函数中用于打印传递给它的字典中的项目的for循环似乎根本没有运行 def TestRewriteRules(base_url, items): """performs tests on the rewrite rules that have been generated""" print(f"base url is: {base_url}

我有下面的Python脚本(请原谅我的粗心大意的编码),我有一个奇怪的问题。下面函数中用于打印传递给它的字典中的项目的for循环似乎根本没有运行

def TestRewriteRules(base_url, items):
  """performs tests on the rewrite rules that have been generated"""
  print(f"base url is: {base_url} need to add more code here")
  for item in items:
    print(f"testing redirect from {base_url}/{urllib3.util.parse_url(item['source']).path} to {urllib3.util.parse_url(item['destination']).url}")
当字典传递给其他函数时,它们似乎运行正常,我发现如果我注释掉
RewriteRuleToFile()
函数调用,就可以运行TestRewrites()中的for循环

完整的脚本如下。任何帮助都将不胜感激

#!/usr/bin/env python3

# accepts a csv file with the following 3 fields: source, destination, redirect_code
# source: the source url for the redirect (domain gets stripped and the path is preserved)
# destination: the destination url for the redirect (full url is preserved)
# redirect_code: the response code for the redirect (e.g, 301, 302)


import csv
import urllib3
import re
import argparse
from time import sleep


def TestRewriteRules(base_url, items):
  """performs tests on the rewrite rules that have been generated"""
  print(f"base url is: {base_url} need to add more code here")
  for item in items:
    print(f"testing redirect from {base_url}/{urllib3.util.parse_url(item['source']).path} to {urllib3.util.parse_url(item['destination']).url}")
    

def ComposeRewrite(items):
  """ composes rewrite rules and returns them as a list """
  rewrite_rules=[] # list to hold our rewrite rules
  for item in items:
    #Skip any rows were all 3 fields are blank
    if(item['source']!= "" and item['destination'] != "" and item['redirect_code'] != ""):
      # compose a new rewrite rule and add it to the list
      
      # Grab the path part of the source url
      source_path = urllib3.util.parse_url(item['source']).path

      ### TODO: Need to make this escaping of url encoded chars more generic and reusable to account for any url encoded character
      ### TODO: have a read of https://serverfault.com/questions/1036007/syntax-for-apache-rewriterule-to-match-encoded-urls-to-fix-character-encodin
      
      source_path=re.sub('%','\\\\x', urllib3.util.parse_url(item['source']).path)

      #Escape dots in the url
      source_path=str(source_path).replace('.', '\.')

      rewrite_rules.append(f"RedirectMatch {item['redirect_code']} ^{source_path}$ {urllib3.util.parse_url(item['destination']).url}\n")
  return rewrite_rules


def RewriteRuleToFile(rules):
  """ write out rewrite rules to a file """
  f = open(rewrites_output_file_path, 'w')
  f.writelines(rules)
  f.close()

# Setup command line argument support
parser=argparse.ArgumentParser()
parser.add_argument("-u", "--urls", help="path to csv file containting the redirect urls we want to process")
parser.add_argument("-o", "--outfile", help="path for the file we want to output the finished redirects to")
parser.add_argument("-t", "--test", help="run tests on rewrite rules", action="store_true")
parser.add_argument("-b", "--baseurl", help="base url of the testing instance if -t or --test is specified")

# Get the values passed to each command line argument
args = parser.parse_args()

csv_path = args.urls #Path the csv file containing the urls we want to process
rewrites_output_file_path = args.outfile # path to write our actual redirects to
testing_base_url = args.baseurl

# Open the CSV file for reading
with open(csv_path, newline='') as csvfile:
  urls = csv.DictReader(csvfile) # Read rows from csv file into a dictionary
  
  # Write rewrite rules to a file
  RewriteRuleToFile(rules=ComposeRewrite(items=urls))

  # Test generated redirects if the --test arg is specified and we have a non-blank --baseurl arg
  if args.test and testing_base_url != None:
    TestRewriteRules(base_url=testing_base_url, items=urls)


  #Debug
  #rewrite_rules = ComposeRewrite(items=urls) # get list of completed rewrite rules
  #for rule in rewrite_rules:
  #  print(rule)
找到解决方案: