Can't import Python module

Question:

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
Asked By: lrhorer

||

Answers:

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
Answered By: Grzegorz Krug

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.

Answered By: CristiFati
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.