I'm running a Python program, condensed below, from the command line, and it gives me an error (name 'cursor' is not defined
) and points to the cursor.fetchmany()
row near the bottom. However, the program runs as desired if I move the first two rows of main()
, the conn
and cursor
assignments, above and outside of main()
into the body of the program. Why doesn't this work when I assign cursor
inside main()
? I'd love to understand whether this is just a quirk of the pyodbc library, or there is a better way to get it to work from inside main()
, or it's actually okay to leave the assignments in the body of the program.
import pyodbc
import csv
# ...other modules...
def main():
conn = pyodbc.connect(DSN=abcxyz, autocommit=True)
cursor = conn.cursor()
# ...sys.argv assignments and validation...
pull_data(query_file, start_date, end_date, out_file)
def pull_data(query_file, start_date, end_date, out_file):
# ...prepare query as string, date range as list...
for date in list_dates:
cursor.execute(query, date)
append_rows(out_file)
def append_rows(out_file):
with open(out_file, 'a', newline='') as file:
writer = csv.writer(file)
while True:
results = cursor.fetchmany(chunk_size)
if not results:
break
for result in results:
writer.writerow(result)
if __name__ == '__main__':
main()