繁体   English   中英

无法导入Python模块

[英]Can't import Python module

我创建了以下名为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

错误实际上在前一行: with open("/run/thermostat/Cursor","w") as f: # Set the Cursor positionwith语句不完整(检查[Python 3.Docs]:复合语句-并附上声明 )。
要更正它,请执行以下操作:

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-Python代码样式指南-缩进 ):

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

您有不正确的缩进块,在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM