在python中,当我从另一个脚本调用一个函数时,我得到一个NameError?

时间:2017-01-21 10:57:21

标签: python function

我认为我犯了一个非常基本的错误,但我似乎无法弄明白。下面提到了错误,但我感到困惑,因为wb中定义了open_xl_file()

当我尝试从另一个脚本调用函数时

import openpyxl
import os
import re

def open_xl_file():
    loc = input("Please enter path of the file:")
    os.chdir(loc)
    file = input("Filename:")
    wb = openpyxl.load_workbook(file)

def sheet_select():
    check = input("Have you called open_xl_file? If yes Press 1 else press 2: ")
    print(check)
    if int(check) != 1:
        open_xl_file()
        sheet = input("Which Sheet do you want to email?\n")
        wb.get_sheet_by_name(sheet)
        sheet
    else:
        sheet = input("Which State do you want to email?\n")
        wb.get_sheet_by_name(sheet)
        sheet

错误日志:

  

NameError:name' wb'没有定义。

3 个答案:

答案 0 :(得分:1)

您需要使用open_xl_filereturn openpyxl.load_workbook(file)返回打开的工作簿,并在wb sheet_select中引用wb = open_xl_file()

import re, openpyxl, os


def open_xl_file():
    loc = input("Please enter path of the file:")
    os.chdir(loc)
    file = input("Filename:")
    return openpyxl.load_workbook(file)

def sheet_select():
    check = input("Have you called open_xl_file? If yes Press 1 else press 2: ")
    print(check)
    wb = open_xl_file()
    if int(check) != 1:
        sheet = input("Which Sheet do you want to email?\n")
        wb.get_sheet_by_name(sheet)
        return sheet
    else:
        sheet = input("Which State do you want to email?\n")
        wb.get_sheet_by_name(sheet)
        return sheet

答案 1 :(得分:0)

原因是变量 wb 在open_xl_file()函数的范围内定义,即仅在此函数内可见(“local”变量)。因此,如果您想在该函数之外使用它,您应该将其设置为全局(非常不推荐),或者从函数中返回

答案 2 :(得分:0)

'wb'未在函数'sheet_select'中定义,您需要将'wb'传递给sheet_select。你可以尝试:

def open_xl_file():
    loc = input("Please enter path of the file:")
    os.chdir(loc)
    file = input("Filename:")
    wb = openpyxl.load_workbook(file)
    return wb

def sheet_select(wb):
    ...

if __name__ == '__main__':
    myWb = open_xl_file()
    sheet_select(myWb)