1

I have created the following Python 3 module named resource.py, with two functions, Read_Cursor and Write_Cursor. When I import the module, I get an error, depending on how I import the module.

I have tried:

import resource
from resource import *
Read_Cursor=resource.Read_Cursor

resource.py:

def Write_Cursor(Cursor):
        with open("/run/thermostat/Cursor","w") as f: # Set the Cursor position

def Read_Cursor():
        with open("/run/thermostat/Cursor","r") as f:   # Get the Cursor position
                C = int(f.read())
        return C

Error:

Traceback (most recent call last):
  File "./index.py", line 6, in <module>
    import resource
  File "/usr/lib/cgi-bin/resource.py", line 5
    def Read_Cursor():
    ^
IndentationError: expected an indented block
lrhorer
  • 373
  • 1
  • 3
  • 12
  • The file `resource.py` is not indented properly. Use a linter like `PyLint` to figure out why. – rdas Jun 16 '19 at 10:06
  • It just returns: ************* Module cgi-bin.resource E: 5, 0: expected an indented block (syntax-error) That's not terribly helpful. – lrhorer Jun 16 '19 at 10:21
  • General tip: If the interpreter says that it "expected" something, and it points to the beginning of the line, then the error is on the previous line more often than not. – Imperishable Night Jun 16 '19 at 12:23

2 Answers2

2

The error is actually at previous line:

with open("/run/thermostat/Cursor","w") as f: # Set the Cursor position`

The with statement is incomplete (check [Python.Docs]: Compound statements - The with statement).

To correct it, do something like:

def Write_Cursor(Cursor):
    with open("/run/thermostat/Cursor", "w") as f: # Set the Cursor position
        f.write(str(Cursor))  # Just an example, I don't know how Cursor should be serialized

Also, as pointed out by others, you should use 4 SPACEs for indentation (as recommended in [Python]: PEP 8 - Style Guide for Python Code - Indentation):

Use 4 spaces per indentation level.

CristiFati
  • 38,250
  • 9
  • 50
  • 87
-2

You got incorrect indented blocks, in Python it is 4 spaces or 1 tabulation

corrected code:

def Write_Cursor(Cursor):
    with open("/run/thermostat/Cursor","w") as f: # Set the Cursor position

def Read_Cursor():
    with open("/run/thermostat/Cursor","r") as f:   # Get the Cursor position
        C = int(f.read())
    return C
Grzegorz Krug
  • 186
  • 2
  • 11
  • 1
    this does nothing to fix the real problem, that there is no code inside the `with` statement in `Write_Cursor` – Robin Zigmond Jun 16 '19 at 10:26
  • 1
    Although *PEP 8* recommends 4 spaces, (if not enforced), **any** indentation can be used, as long it's consistent. The answer is incorrect. -1. – CristiFati Jun 16 '19 at 10:29
  • 1
    Correct! You have sharp eyes. Like everyone else, I was looking at the indents. It never occurred to me I had left out the write. – lrhorer Jun 16 '19 at 10:36