【问题标题】:Unable to pass data in variables between functions无法在函数之间传递变量中的数据
【发布时间】:2017-10-23 20:43:48
【问题描述】:

我对 Python 还很陌生。我熟悉跨函数传递数据的概念。

理论上,

def c():
   r = raw_input("Ask Something? ")
   ..
   return r

def p(x):
    ...
    do something

r = c()
p(r)

下面的代码可以通过终端 (python filename.py file.txt) 正常工作,但我想添加工作流,其中变量存储文件的路径并将其传递给函数 (processFile)。我只是无法获取传递给函数的数据/值。

这是我要编辑的代码:

def registerException(exc):
    exceptions[exc] += 1

def processFile(x):
  with open(x, "r") as fh:
    currentMatch = None
    lastLine = None
    addNextLine = False
    for line in fh.readlines():
      if addNextLine and currentMatch != None:
         addNextLine = False
         currentMatch += line
         continue
      match = REGEX.search(line) != None
      if match and currentMatch != None:
         currentMatch += line
      elif match:
         currentMatch = lastLine + line
      else:
         if currentMatch != None:
            registerException(currentMatch)
         currentMatch = None
      lastLine = line
      addNextLine = CONT.search(line) != None
    # If last line in file was a stack trace
    if currentMatch != None:
      registerException(currentMatch)

for f in sys.argv[1:]:
  processFile(f)

for item in sorted(exceptions.items(), key=lambda e: e[1], reverse=True):
  print item[1], ":", item[0]

我将变量声明为全局变量还是局部变量都没有关系。有人可以帮我解决这个问题吗?

编辑 1:

我已应用 Daniel 建议的更改,现在我得到:TypeError: 'NoneType' object is not iterable.

下面是代码:

def c():
    path = raw_input("Path to file? ")
    r = os.path.abspath(path)

def process_file(filename):
    current = None
    last_line = None
    continue_line = False
    with open(filename, "r") as fh:
        for line in fh:
            if continue_line and current is not None:
               continue_line = False
               current += line
               continue
            if REGEX.search(line):
               if current is None:
                  current = last_line
               current += line
            else:
               if current is not None:
                  yield current
               current = None
            last_line = line
            continue_line = CONT.search(line)
        # If last line in file was a stack trace
        if current is not None:
            yield current

def process_files(filenames):
    exceptions = defaultdict(int)
    for filename in filenames:
        for exc in process_file(filename):
            exceptions[exc] += 1

for item in sorted(exceptions.items(), key=lambda e: e[1], reverse=True):
    print item[1], ":", item[0]

r = c()
process_files(r)

我进行了一些更改并删除了 sys.argv[1],因为它在运行脚本时需要命令行参数。

我认为我得到的新错误是由于操作系统路径造成的。我怎样才能解决这个问题 ?

【问题讨论】:

  • 你在说什么变量?
  • 嗨,马克,如果我在 processfile 函数之前添加一个变量 x = pathtofile ,由于某种原因,该值不会被传递。我已经尝试将它创建为全局和本地。我也尝试创建一个函数来捕获此变量并将其传递给 processfile 函数,但结果仍然相同。代码可以通过终端(python file.py log.txt)正常运行,但我们希望在代码中硬编码路径文件。

标签: python python-2.7 function variables global-variables


【解决方案1】:

exceptions 也是一个参数,必须传递给所有函数。或者,您可以将processFile 写为生成器,内联registerException

def process_file(filename):
    current = None
    last_line = None
    continue_line = False
    with open(filename, "r") as fh:
        for line in fh:
            if continue_line and current is not None:
                continue_line = False
                current += line
                continue
            if REGEX.search(line):
                if current is None:
                    current = last_line
                current += line
            else:
                if current is not None:
                    yield current
                current = None
            last_line = line
            continue_line = CONT.search(line)
        # If last line in file was a stack trace
        if current is not None:
            yield current

def process_files(filenames)
    exceptions = defaultdict(int)
    for filename in filenames:
        for exc in process_file(filename):
            exceptions[exc] += 1

    for item in sorted(exceptions.items(), key=lambda e: e[1], reverse=True):
        print item[1], ":", item[0]

process_files(sys.argv[1:])

【讨论】:

  • 感谢您的意见丹尼尔。但仍然存在原来的问题。我知道它可以通过终端(python file.py log.txt)运行得很好,但是我将如何在代码中对路径进行硬编码?我尝试先声明一个全局变量,然后声明一个局部变量,但是 process_file 函数没有看到这个变量。
  • 您可以使用任何文件名列表调用process_files,甚至是硬编码的。
  • 谢谢丹尼尔!感谢您的建议,我终于让它工作了!我错过了 process_files([r]) !!!
猜你喜欢
  • 2020-07-02
  • 2013-04-09
  • 2013-03-07
  • 1970-01-01
  • 1970-01-01
  • 2012-10-31
  • 1970-01-01
相关资源
最近更新 更多