Python:更改:如何使局部变量成为全局变量?

时间:2018-12-02 21:24:55

标签: python gspread

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pprint

scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)

def openSheet():
    shname = str(input("Enter existing sheet name >> "))
    sheet = client.open(shname).sheet1
    term()

def createSheet():
    shnname = str(input("Enter new sheet name >> "))
    mail = str(input("Enter mail address >> "))
    sheetn = client.create(shnname)
    sheetn.share(mail, perm_type='user', role='owner')
    term()

def help():
    print("openSheet - open spreadsheet (do this befor any other command [except createSheet])")
    print("createSheet - create spreadsheet and transfer ownership")
    print("printAll - print all data from spreadsheet")
    print("printCol - print data from specified column")
    print("printRow - print data from specified row")
    print("printCell - print data from the one, specified cell")
    print("changeCell - change data in one, specified cell")
    print("help - displays all the functions and their description")
    print("exit - closes the program")
    term()

def changeCell():
    x = int(input("Enter number of col >> "))
    y = int(input("Enter number of row >> "))

    pp = pprint.PrettyPrinter()
    data = sheet.cell(y,x).value
    pp.pprint(data)

    upd = str(input("Enter data >> "))

    sheet.update_cell(y, x, upd)
    data = sheet.cell(y,x).value
    pp.pprint(data)
    term()

def printCell():
    x = int(input("Enter number of col >> "))
    y = int(input("Enter number of row >> "))

    pp = pprint.PrettyPrinter()
    data = sheet.cell(y,x).value
    pp.pprint(data)
    term()

def printRow():
    y = int(input("Enter number of row >> "))

    pp = pprint.PrettyPrinter()
    data = sheet.row_values(y)
    pp.pprint(data)
    term()

def printCol():
    x = int(input("Enter number of col >> "))

    pp = pprint.PrettyPrinter()
    data = sheet.col_values(x)
    pp.pprint(data)
    term()

def printAll():
    pp = pprint.PrettyPrinter()
    data = sheet.get_all_values()
    pp.pprint(data)
    term()

def none():
    term()

def term():
    terminal = str(input(">> "))

    if (terminal == "openSheet"):
        openSheet()
    if (terminal == "createSheet"):
        createSheet()
    if (terminal == "printAll"):
        printAll()
    if (terminal == "printCell"):
        printCell()
    if (terminal == "changeCell"):
        changeCell()
    if (terminal == "printCol"):
        printCol()
    if (terminal == "printRow"):
        printRow()
    if (terminal == "help"):
        help()
    if (terminal == "exit"):
        exit()
    else:
        none()

term()

因此,当我在终端中运行此命令并键入openSheet时,输入电子表格的名称并键入printAll,我得到以下信息:

>> openSheet
Enter existing sheet name >> values
>> printAll
Traceback (most recent call last):
  File "/home/luky/sheets/sheets.py", line 106, in <module>
    term()
  File "/home/luky/sheets/sheets.py", line 86, in term
    openSheet()
  File "/home/luky/sheets/sheets.py", line 12, in openSheet
    term()
  File "/home/luky/sheets/sheets.py", line 90, in term
    printAll()
  File "/home/luky/sheets/sheets.py", line 75, in printAll
    data = sheet.get_all_values()
NameError: name 'sheet' is not defined

显然,未定义工作表。我不知道如何解决它。 我在想,它不会将任何东西赋给工作表变量,因此它无法读取其中的内容。不知道。当我不使用openSheet作为函数时,它会起作用。

1 个答案:

答案 0 :(得分:1)

使用global关键字

# Hello World program in Python


def foo():
    global bar #Define the global variable bar
    bar = "Hello world" #Set bar to hello world

foo() #Set bar
print bar #Hello world



#Second example


fo = "Initial value" #Initial value


def foobar():
    global fo
    fo = "Value changed"
    bar = "Value changed" #Global variable 'bar' isn't changed because we didn't declare bar global in this function. There is only a local variable named 'bar' created.

print fo #Initial value
print bar #Hello world

foobar() #Change value

print fo #Value changed
print bar #Hello world

http://tpcg.io/yUvZD8(尝试一下)

永远不要将变量设置为全局变量,只需在函数开头将其声明为全局变量并更改值即可。