借助InteractiveInterpreter.runsource()
方法,我們可以使用編譯並運行具有單行或多行的源InteractiveInterpreter.runsource()
方法。
用法: InteractiveInterpreter.runsource(code)
返回:如果編譯成功,則返回輸出,否則返回false並返回錯誤。
範例1:
在這個例子中,我們可以通過使用InteractiveInterpreter.runsource()
方法,我們能夠編譯並運行這段代碼,如果運行成功,則可以使用此方法將結果返回false。
# import code and InteractiveInterpreter
from code import InteractiveInterpreter
code = 'print("GeeksForGeeks")'
# Using InteractiveInterpreter.runsource() method
InteractiveInterpreter().runsource(code)
輸出:
GeeksForGeeks
範例2:
# import code and InteractiveInterpreter
from code import InteractiveInterpreter
code = 'a = 8; b = 2.5; -a = a + b'
# Using InteractiveInterpreter.runsource() method
InteractiveInterpreter().runsource(code)
輸出:
SyntaxError:can’t assign to operator
False
相關用法
注:本文由純淨天空篩選整理自Jitender_1998大神的英文原創作品 InteractiveInterpreter runsource() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。