Python 2 和 Python 3 差異

本主題討論 Python 2 與 3 之間的差異,因為它適用於 編排與自動化 應用程式。

Python 文件詳細說明 Python 2 與 Python 3 之間的差異。 例如,請參閱 Python 3.0中的新增功能。 此外,您還需要注意在 編排與自動化環境定義中套用的差異。

匯入模組

Script 特性可讓您在撰寫 Script 時匯入 Python 模組。 如果 語言 欄位設為 Python 2 ,則您只能匯入 java.util.Datere 模組。 如果設為 Python 3 ,您可以匯入下列模組:
  • array
  • base64
  • bs4
  • 行事曆
  • Collection
  • datetime (相當於 Python 2 java.util.Date 模組)
  • 電子郵件
  • enum
  • 雜湊利卜
  • html
  • html2text
  • json
  • 隨機
  • 回覆
  • regex
  • 字串
  • 時間
  • xml
此外,下列 Python 內建程式僅適用於 Python 3 Script:
  • all ()
  • any ()
  • bytearray ()
  • bytes ()
  • classmethod
  • staticmethod
  • type ()

錯誤類型

Python 3 實作引進兩種新的錯誤類型:
  • ResilientSecurity如果 Script 嘗試違反安全限制,則會發生異常狀況。
  • 如果 Script 嘗試配置超過允許的 RAM 數量上限 (64MB) ,則會發生 ResilientMemoryLimitException 。

'from' 關鍵字

Python 3 中的 from 關鍵字與電子郵件訊息環境定義物件中的 from 屬性衝突。 因此,在 Python 3 Script 中不支援使用 emailmessage.from ,應該取代為 emailmessage.sender。 Python 2 仍然支援 emailmessage.from

不存在的欄位

在 Python 2 中,嘗試存取不存在的環境定義物件屬性會成功,並傳回 None。 不過,在 Python 3 中,相同的作業會擲出屬性錯誤,指出欄位名稱無效。 此行為與標準 Python 3 一致。 hasattr() 方法可用來檢查屬性是否存在。 例如:
if hasattr(incident, 'nonExistentField'):
  log.info(incident.nonExistentField)
else:
  log.info('Tried to access a field that does not exist')
Script 會傳回下列日誌訊息:
INFO: Cannot access a field that does not exist.

Unicode 支援

Python 3 支援現成可用的 Unicode。 這表示您不再需要明確使用 u 字首或 unicode () 函數將字串儲存為 Unicode。 如果您將現有 Script 從 Python 2 轉換為 Python 3 ,則必須檢查並移除這些元素,以避免 Python 3 中與 Unicode 相關的錯誤。 如需相關資訊,請參閱 Python 3 文件 https://docs.python.org/3.6/howto/unicode.html

文字物件資料類型

文字物件資料類型在 Python 2 和 Python 3 中的行為不同。 這些差異不一定會岔斷從 Python 2 轉換至 3 的 Script ,但可能感興趣。
  • 在 Python 3 中,無論您使用簡式字串或 helper 函數來設定文字區欄位的值,該值都會儲存為 TextObject。 在 Python 2 中,如果您使用簡式字串來設定文字區欄位的值,則該值會儲存為 Unicode 物件。 如果您使用 helper 函數來設定它,則值會儲存為 SimpleTextContentDTO。
  • 在 Python 3 中, TextObject 類型的物件預設格式為 'html'。 只有在呼叫 helper.createPlainText()來設定欄位值時,才會將格式設為 'text'。 在 Python 2 中,類型為 SimpleTextContentDTO 的物件格式可能是 TEXT 或 HTML ,視呼叫以設定值的 Helper 而定。
您可以執行下列 Script 並檢查日誌訊息,以探索 Python 版本中的差異:
incident.description = 'set direct'
log.info(type(incident.description)) 

incident.description = helper.createPlainText('set using createPlainText helper') 
log.info(type(incident.description)) 

incident.description = helper.createRichText('set using createRichText helper') 
log.info(type(incident.description))