无法导入Python模块

时间:2019-06-16 10:03:46

标签: python

我创建了以下名为resource.py的Python 3模块,其中包含两个函数Read_Cursor和Write_Cursor。导入模块时,会出现错误,具体取决于导入模块的方式。

我尝试过:

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

错误:

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

2 个答案:

答案 0 :(得分:2)

错误实际上出在前一行:with open("/run/thermostat/Cursor","w") as f: # Set the Cursor position with 语句不完整(选中[Python 3.Docs]: Compound statements - The with statement)。
要纠正它,请执行以下操作:

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

此外,正如其他人指出的那样,您应该使用 4 SPACE 进行缩进(如[Python]: PEP 8 -- Style Guide for Python Code - Indentation中的建议):

  

每个缩进级别使用4个空格。

答案 1 :(得分:-2)

您有不正确的缩进块,在Python中是4个空格或1个制表符

更正的代码:

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