Python: Изменение: как сделать локальную переменную глобальной?

1
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
    Это не имеет ничего общего с тем, что gspread не держит соединение открытым, вы просто неправильно понимаете границы. Переменные, определенные внутри функций, не будут доступны вне этой функции, без global , и вы не хотите идти по этому пути
  • 0
    Почему нет? Как я могу это сделать?
Показать ещё 1 комментарий
Теги:
gspread

2 ответа

0

Использовать 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 (Попробуйте)

Никогда не делайте переменную global, просто объявите ее глобальной в начале функции и измените значение.

0

При определении переменной, то только в пределах метода, класса или цикл, в котором она была определена (существует целый ряд ресурсов, которые объясняют переменный объем более подробно, например).

Хотя это не самая лучшая практика, самым простым решением было бы хранить переменную листа глобально, как показано ниже.

import ...

sheet = None

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

Ещё вопросы

Сообщество Overcoder
Наверх
Меню