【问题标题】:python script not working when written as function编写为函数时python脚本不起作用
【发布时间】:2020-01-31 08:22:06
【问题描述】:

我有一个 python 脚本,它可以找到两个文件之间的区别,它工作正常,但是当我尝试将它编写为一个函数时,它不起作用。

    def diff_tool ():

    with open('C:\\Users\\rites\\Downloads\\2018temp_new.json', encoding="utf-8") as f1:
        f1_text = f1.read().splitlines()
    with open('C:\\Users\\rites\\Downloads\\2019tempnew.json', encoding="utf-8") as f2:
        f2_text = f2.read().splitlines()

   # Find and print the diff:
    diffile= []
    diff = difflib.Differ()
    for line in diff.compare(f1_text, f2_text):
        #json.dump(line,f, indent=2)
        if line.startswith(("-", "+", "?")):
            diffile.append(line)
            #print (line, file=f)]updated=[]
            #lines = diff.splitlines()
            updated, deleted, inserted = [],[],[]
            lines = [line for line in diffile if line.find('"header"') == -1]
            for i in range(len(lines)):
                try:
                    if lines[i+1].startswith('?'):
                        if lines[i].startswith('-'):
                            updated.append(lines[i])
                            updated.append (lines[i+1])
                    else:
                        if lines[i].startswith('+'):
                            deleted.append(lines[i])
                        elif lines[i].startswith('-'):
                            inserted.append(lines[i])
                except IndexError:
                    continue
            lists = ["updated", "deleted", "inserted"]
            data = {listname: globals()[listname] for listname in lists}
            with open ('diff_result.json', 'w', encoding='utf-8') as outfile:
                json.dump(data,outfile)

我想把它写成函数,以后我想把它作为服务。我是 python 新手并尝试一下。

当我在 python 控制台中运行它时,我遇到了关键错误-

 data = {listname: globals()[listname] for listname in lists}
KeyError: 'updated'

存在“更新”键。

【问题讨论】:

  • 怎么不工作了?它会产生错误吗?它什么都不做吗?
  • 你试过调用这个函数吗?添加到文件中:diff_tool(f1_text, f2_text)

标签: python python-3.x function


【解决方案1】:

正如 Yann 所说,您需要调用函数:

diff_tool(f1_text, f2_text)

并确保在您的 with 语句之后调用它。

【讨论】:

  • 我试图在 python 控制台中运行它,它正在抛出关键错误。当我将它作为脚本运行时,它运行良好。
猜你喜欢
  • 1970-01-01
  • 2014-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 2021-08-26
相关资源
最近更新 更多