簡體   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